This repository has been archived by the owner on Jun 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
reader.js
90 lines (85 loc) · 2.41 KB
/
reader.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
export default multiformats => {
const { CID } = multiformats
/* eslint-disable max-depth */
const links = function * (decoded, path = []) {
if (typeof decoded !== 'object' || !decoded) return
for (const key of Object.keys(decoded)) {
const _path = path.slice()
_path.push(key)
const val = decoded[key]
if (val && typeof val === 'object') {
if (Array.isArray(val)) {
for (let i = 0; i < val.length; i++) {
const __path = _path.slice()
__path.push(i)
const o = val[i]
const cid = CID.asCID(o)
if (cid) {
yield [__path.join('/'), cid]
} else if (typeof o === 'object') {
yield * links(o, __path)
}
}
} else {
const cid = CID.asCID(val)
if (cid) {
yield [_path.join('/'), cid]
} else {
yield * links(val, _path)
}
}
}
}
}
const tree = function * (decoded, path = []) {
if (typeof decoded !== 'object' || !decoded) return
for (const key of Object.keys(decoded)) {
const _path = path.slice()
_path.push(key)
yield _path.join('/')
const val = decoded[key]
if (val && typeof val === 'object' && !CID.asCID(val)) {
if (Array.isArray(val)) {
for (let i = 0; i < val.length; i++) {
const __path = _path.slice()
__path.push(i)
const o = val[i]
yield __path.join('/')
if (typeof o === 'object' && !CID.asCID(o)) {
yield * tree(o, __path)
}
}
} else {
yield * tree(val, _path)
}
}
}
}
/* eslint-enable max-depth */
class Reader {
constructor (decoded) {
Object.defineProperty(this, 'decoded', {
get: () => decoded
})
}
get (path) {
let node = this.decoded
path = path.split('/').filter(x => x)
while (path.length) {
const key = path.shift()
if (node[key] === undefined) { throw new Error(`Object has no property ${key}`) }
node = node[key]
const cid = CID.asCID(node)
if (cid) return { value: cid, remaining: path.join('/') }
}
return { value: node }
}
links () {
return links(this.decoded)
}
tree () {
return tree(this.decoded)
}
}
return decoded => new Reader(decoded)
}