This repository has been archived by the owner on Feb 12, 2024. It is now read-only.
/
dag.js
118 lines (97 loc) · 3.04 KB
/
dag.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
'use strict'
const promisify = require('promisify-es6')
const CID = require('cids')
const pull = require('pull-stream')
const mapAsync = require('async/map')
const flattenDeep = require('lodash.flattendeep')
module.exports = function dag (self) {
return {
put: promisify((dagNode, options, callback) => {
if (typeof options === 'function') {
callback = options
} else if (options.cid && options.format && options.hashAlg) {
throw new Error('Can\'t put dag node. Please provide either `cid` OR `format` and `hashAlg` options.')
} else if ((options.format && !options.hashAlg) || (!options.format && options.hashAlg)) {
throw new Error('Can\'t put dag node. Please provide `format` AND `hashAlg` options.')
}
const optionDefaults = {
format: 'dag-cbor',
hashAlg: 'sha2-255'
}
options = options.cid ? options : Object.assign({}, optionDefaults, options)
self._ipld.put(dagNode, options, callback)
}),
get: promisify((cid, path, options, callback) => {
if (typeof path === 'function') {
callback = path
path = undefined
}
if (typeof options === 'function') {
callback = options
options = {}
}
options = options || {}
if (typeof cid === 'string') {
const split = cid.split('/')
cid = new CID(split[0])
split.shift()
if (split.length > 0) {
path = split.join('/')
} else {
path = '/'
}
} else if (Buffer.isBuffer(cid)) {
try {
cid = new CID(cid)
} catch (err) {
return callback(err)
}
}
self._ipld.get(cid, path, options, callback)
}),
tree: promisify((cid, path, options, callback) => {
if (typeof path === 'object') {
callback = options
options = path
path = undefined
}
if (typeof path === 'function') {
callback = path
path = undefined
}
if (typeof options === 'function') {
callback = options
options = {}
}
options = options || {}
if (typeof cid === 'string') {
const split = cid.split('/')
cid = new CID(split[0])
split.shift()
if (split.length > 0) {
path = split.join('/')
} else {
path = undefined
}
}
pull(
self._ipld.treeStream(cid, path, options),
pull.collect(callback)
)
}),
// TODO - use IPLD selectors once they are implemented
_getRecursive: promisify((multihash, callback) => {
// gets flat array of all DAGNodes in tree given by multihash
self.dag.get(new CID(multihash), (err, res) => {
if (err) { return callback(err) }
mapAsync(res.value.links, (link, cb) => {
self.dag._getRecursive(link.multihash, cb)
}, (err, nodes) => {
// console.log('nodes:', nodes)
if (err) return callback(err)
callback(null, flattenDeep([res.value, nodes]))
})
})
})
}
}