-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsolution.js
74 lines (59 loc) · 1.57 KB
/
solution.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
const EventEmitter = require('events')
const hyperdb = require('hyperdb')
const hyperid = require('hyperid')
const pump = require('pump')
const forEachChunk = require('../../lib/for-each-chunk')
const uuid = hyperid()
module.exports = class Saga extends EventEmitter {
constructor (storage, key, username) {
super()
this.messages = new Map()
this.users = new Map()
this.username = username
this.timestamp = Date.now()
this.db = hyperdb(storage, key, { valueEncoding: 'json' })
}
async initialize () {
await this._ready()
this._updateHistory(this._watchForMessages.bind(this))
}
writeMessage (message) {
const key = `messages/${uuid()}`
const data = {
key,
message,
username: this.username,
timestamp: Date.now()
}
return new Promise((resolve, reject) => {
this.db.put(key, data, (err) => {
if (err) return reject(err)
resolve(key)
})
})
}
_updateHistory (onFinish) {
const h = this.db.createHistoryStream({ reverse: true })
const ws = forEachChunk({ objectMode: true }, (data, enc, next) => {
const { key, value } = data
if (/messages/.test(key)) {
if (this.messages.has(key)) {
h.destroy()
return
}
this.messages.set(key, value)
this.emit('message', value, key)
}
next()
})
pump(h, ws, onFinish)
}
_watchForMessages () {
this.db.watch('messages', () => {
this._updateHistory()
})
}
_ready () {
return new Promise(resolve => this.db.ready(resolve))
}
}