Files: 612509945be4d8cb719d3b0a5a0390a0ddbcf911 / lib / mutant-pull-dict.js
1572 bytesRaw
1 | const pull = require('pull-stream') |
2 | const Abortable = require('pull-abortable') |
3 | const LazyWatcher = require('mutant/lib/lazy-watcher') |
4 | const Value = require('mutant/value') |
5 | |
6 | module.exports = createPullDict |
7 | |
8 | function createPullDict (getStream, { nextTick = null, idle = null, checkDelete = null, sync = null } = {}) { |
9 | const state = { getStream, checkDelete } |
10 | const binder = LazyWatcher.call(state, update, listen, unlisten) |
11 | binder.value = {} |
12 | if (nextTick) binder.nextTick = true |
13 | if (idle) binder.idle = true |
14 | state.binder = binder |
15 | const result = MutantPullDict.bind(state) |
16 | if (sync) { |
17 | state.sync = result.sync = Value(false) |
18 | } |
19 | return result |
20 | } |
21 | |
22 | function MutantPullDict (listener) { |
23 | if (!listener) { |
24 | return this.binder.getValue() |
25 | } |
26 | return this.binder.addListener(listener) |
27 | } |
28 | |
29 | function update () { |
30 | // this is only run on the item when no one is listening (use a onceTrue instead of resolve) |
31 | // since we don't have an synchronous way to check, ignore |
32 | } |
33 | |
34 | function listen () { |
35 | const abortable = Abortable() |
36 | this.abort = abortable.abort |
37 | pull( |
38 | this.getStream(), |
39 | abortable, |
40 | pull.drain((value) => { |
41 | if (this.sync && !this.sync()) this.sync.set(true) |
42 | Object.keys(value).forEach((key) => { |
43 | if (typeof this.checkDelete === 'function' && this.checkDelete(value[key])) { |
44 | delete value[key] |
45 | } else { |
46 | this.binder.value[key] = value[key] |
47 | } |
48 | }) |
49 | this.binder.broadcast() |
50 | }) |
51 | ) |
52 | } |
53 | |
54 | function unlisten () { |
55 | if (this.abort) { |
56 | this.abort() |
57 | this.abort = null |
58 | } |
59 | } |
60 |
Built with git-ssb-web