git ssb

0+

regular / ssb-cms



Tree: 43af34efb145e2705ff168ae3e6f3cc6832314ac

Files: 43af34efb145e2705ff168ae3e6f3cc6832314ac / db.js

2436 bytesRaw
1const ref = require('ssb-ref')
2const pull = require('pull-stream')
3const many = require('pull-many')
4const {isDraft} = require('./util')
5
6module.exports = function(ssb, drafts) {
7
8 function getMessageOrDraft(id, cb) {
9 //console.log('getting', id)
10 if (isDraft(id)) drafts.get(id, cb)
11 else if (ref.isMsg(id)) ssb.get(id, cb)
12 else cb(Error(`getMessageOrDraft: invalid id: ${id}`))
13 }
14
15 function filterSync(sync) {
16 return pull.filter( x => {
17 // only pass through the last expected sync
18 if (sync && x.sync) {
19 //console.log('sync, expect more:', sync-1)
20 return (!--sync)
21 }
22 return true
23 })
24 }
25
26 function uniqueKeys() {
27 let seenKeys = [] // TODO: use a Set here?
28 return pull.filter( x => {
29 if (x.type !== 'del' && x.key) {
30 if (seenKeys.includes(x.key)) {
31 return false
32 }
33 seenKeys.push(x.key)
34 }
35 return true
36 })
37 }
38
39 function branches(root, opts) {
40 if (!root) throw new Error('Missing argument: root')
41 opts = opts || {}
42 let syncCount = opts.sync ? (ref.isMsg(root) ? 2 : 1) : 0
43 return pull(
44 many([
45 ref.isMsg(root) ? pull(
46 ssb.links(Object.assign({}, opts, {
47 rel: 'branch',
48 dest: root,
49 keys: true,
50 values: true
51 }))
52 ) : pull.empty(),
53 drafts.byBranch(root, opts)
54 ]),
55 uniqueKeys(),
56 // TODO: do we actually need to de-duplicate the keys?
57 // Why?
58 filterSync(syncCount)
59 )
60 }
61
62 function revisions(root, opts) {
63 if (!root) throw new Error('Missing argument: root')
64 opts = opts || {}
65 let syncCount = opts.sync ? (ref.isMsg(root) ? 3 : 2) : 1
66 return pull(
67 many([
68 pull(
69 pull.once(root),
70 pull.asyncMap(getMessageOrDraft),
71 pull.map( value => opts.sync ? [
72 { key: root, value},
73 { sync: true }
74 ] : [
75 { key: root, value}
76 ]),
77 pull.flatten()
78 ),
79 ref.isMsg(root) ? pull(
80 ssb.links(Object.assign({}, opts, {
81 rel: 'revisionRoot',
82 dest: root,
83 keys: true,
84 values: true
85 }))
86 ) : pull.empty(),
87 drafts.byRevisionRoot(root, opts)
88 ]),
89 uniqueKeys(),
90 filterSync(syncCount)
91 )
92 }
93
94 return {
95 getMessageOrDraft,
96 branches,
97 revisions
98 }
99}
100

Built with git-ssb-web