Files: b3369beb8b305b3fd5c63b483fdd8810799b0e2d / book / pull / db.js
2252 bytesRaw
1 | const pull = require('pull-stream') |
2 | const nest = require('depnest') |
3 | |
4 | exports.gives = nest({ |
5 | 'book.pull': ['get', 'getAll', 'create', 'amend'] |
6 | }) |
7 | |
8 | exports.needs = nest({ |
9 | 'sbot.pull.messagesByType': 'first', |
10 | 'sbot.pull.links': 'first', |
11 | 'sbot.async.get': 'first', |
12 | 'sbot.async.publish': 'first' |
13 | }) |
14 | |
15 | exports.create = function (api) { |
16 | |
17 | return nest({ |
18 | 'book.pull.get': get, |
19 | 'book.pull.getAll': getAll, |
20 | 'book.pull.create': create, |
21 | 'book.pull.amend': amend |
22 | }) |
23 | |
24 | function create(commonObj, subjectiveObj, cb) |
25 | { |
26 | api.sbot.async.publish({ type: 'bookclub', |
27 | common: commonObj, |
28 | subjective: subjectiveObj }, cb) |
29 | } |
30 | |
31 | function amend(id, commonObj, subjectiveObj, cb) |
32 | { |
33 | let msg = { type: 'bookclub-update', root: id } |
34 | if (commonObj) |
35 | msg.common = commonObj |
36 | if (subjectiveObj) |
37 | msg.subjective = subjectiveObj |
38 | |
39 | api.sbot.async.publish(msg, cb) |
40 | } |
41 | |
42 | function get(key, cb) { |
43 | pull( |
44 | api.sbot.async.get(key), |
45 | pull.asyncMap((msg, cb) => hydrate(msg, cb)), |
46 | pull.drain(book => cb(book)) |
47 | ) |
48 | } |
49 | |
50 | function getAll(cb) { |
51 | pull( |
52 | api.sbot.pull.messagesByType({ type: 'bookclub', fillCache: true, keys: false }), |
53 | pull.asyncMap((msg, cb) => hydrate(msg, cb)), |
54 | pull.collect((books) => { |
55 | cb([books]) // FIXME: array? |
56 | }) |
57 | ) |
58 | } |
59 | |
60 | // internal |
61 | |
62 | function applyAmends(book, cb) { |
63 | pull( |
64 | api.sbot.pull.links({ dest: book.key }), // live: true |
65 | pull.filter(data => data.key), |
66 | pull.asyncMap((data, cb) => { |
67 | api.sbot.async.get(data.key, cb) |
68 | }), |
69 | pull.collect((err, msgs) => { // for live use drain |
70 | if (err) throw err |
71 | |
72 | msgs.forEach(msg => { |
73 | book.common = Object.assign(book.common, msg.content.common) |
74 | book.subjective[msg.author] = Object.assign(book.subjective[msg.author], |
75 | msg.content.subjective) |
76 | }) |
77 | |
78 | cb(book) |
79 | }) |
80 | ) |
81 | } |
82 | |
83 | function hydrate(msg, cb) |
84 | { |
85 | var book = { |
86 | key: msg.key, |
87 | common: msg.content.common, |
88 | subjective: {} |
89 | } |
90 | book.subjective[msg.author] = msg.content.subjective |
91 | |
92 | applyAmends(book, cb) |
93 | } |
94 | } |
95 |
Built with git-ssb-web