-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.js
86 lines (73 loc) · 2.05 KB
/
core.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const kappacore = require('kappa-core')
const views = require('./views')
const memdb = require('memdb')
const swarm = require('./swarm')
const cuid = require('cuid')
module.exports = createBucko
async function createBucko (topicName, localRef = '') {
// for local testing localRef help us in differentiating between clients,
// we can pass a 1, 2, 3 etc
const topic = slug(topicName)
const databasePath = `./bucko-${topic}${localRef}`
const core = kappacore(databasePath, { valueEncoding: 'json' })
const db = memdb()
core.use('chat', views.createMessagesView(db))
const feed = await getFeed(core)
const head = await getHead(feed()).catch(err => ({})) // eslint-disable-line
let nickname = head.nickname || createNickname()
// Important to join the swarm once the local writer is initialized
swarm(core, topic)
return {
publish: (message) => publish(message, feed(), nickname),
addNickname: (newNickname) => { nickname = newNickname },
getNickname: () => nickname,
readTail: (fn) => tail(core, fn)
}
}
function getHead (feed) {
return new Promise((resolve, reject) => {
feed.head((err, data) => {
if (err) reject(err)
resolve(data)
})
})
}
function tail (core, fn) {
core.api.chat.tail(1, (data) => fn(data[0]))
}
function publish (message, feed, nickname) {
return new Promise((resolve, reject) => {
feed.append({
type: 'chat',
nickname,
text: message,
timestamp: getTimestamp()
}, function (err) {
if (err) reject(err)
resolve(message)
})
})
}
function getTimestamp () {
return new Date().toISOString()
}
async function getFeed (core) {
const feed = await createWriter(core)
return () => feed
}
function createWriter (core) {
return new Promise((resolve, reject) => {
core.ready(function () {
core.writer('local', (err, feed) => {
if (err) reject(err)
resolve(feed)
})
})
})
}
function createNickname () {
return cuid().slice(-7)
}
function slug (s) {
return s.trim().toLocaleLowerCase().replace(/\s/g, '-')
}