-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathEventedDatastore.js
More file actions
70 lines (55 loc) · 2.05 KB
/
Copy pathEventedDatastore.js
File metadata and controls
70 lines (55 loc) · 2.05 KB
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
const EventEmitter = require('events')
const Datastore = require('@seald-io/nedb') // nedb doesn't provide listeners on DB events by default
// Wraps @seald-io/nedb's public insert/remove methods (instead of patching
// private internals, which aren't part of the fork's stable API) to emit
// 'inserted'/'removed' events with the affected document(s).
class EventedDatastore extends Datastore {
constructor (options) {
super(options)
this.__events = new EventEmitter()
}
on (eventType, listener) {
return this.__events.on(eventType, listener)
}
once (eventType, listener) {
return this.__events.once(eventType, listener)
}
off (eventType, listener) {
return this.__events.removeListener(eventType, listener)
}
listeners (eventType) {
return this.__events.listeners(eventType)
}
insert (newDoc, callback) {
const cb = callback || function () {}
return super.insert(newDoc, (err, insertedDoc) => {
if (err) return cb(err)
if (this.__events.listeners('inserted').length > 0) {
const insertedDocs = Array.isArray(insertedDoc) ? insertedDoc : [insertedDoc]
insertedDocs.forEach((doc) => this.__events.emit('inserted', doc))
}
cb(null, insertedDoc)
})
}
remove (query, options, callback) {
if (typeof options === 'function') {
callback = options
options = {}
}
const cb = callback || function () {}
// nedb's remove() only returns the count of removed documents, so we
// need to look the matching docs up beforehand to emit their content.
super.find(query, (findErr, matchedDocs) => {
if (findErr) return cb(findErr)
super.remove(query, options, (err, numRemoved) => {
if (err) return cb(err)
if (this.__events.listeners('removed').length > 0 && numRemoved > 0) {
const removedDocs = options.multi ? matchedDocs : matchedDocs.slice(0, numRemoved)
removedDocs.forEach((doc) => this.__events.emit('removed', doc))
}
cb(null, numRemoved)
})
})
}
}
module.exports = EventedDatastore