This repository was archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathlinks.js
88 lines (73 loc) · 1.78 KB
/
links.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
'use strict'
const dagPb = require('@ipld/dag-pb')
const dagCbor = require('@ipld/dag-cbor')
const raw = require('multiformats/codecs/raw')
const { CID } = require('multiformats/cid')
const withTimeoutOption = require('ipfs-core-utils/src/with-timeout-option')
/**
* @typedef {import('@ipld/dag-pb').PBLink} DAGLink
*/
/**
* @param {any} node
* @param {DAGLink[]} [links]
* @returns {DAGLink[]}
*/
function findLinks (node, links = []) {
for (const key in node) {
const val = node[key]
if (key === '/' && Object.keys(node).length === 1) {
try {
links.push({
Name: '',
Tsize: 0,
Hash: CID.parse(val)
})
continue
} catch (_) {
// not a CID
}
}
const cid = CID.asCID(val)
if (cid) {
links.push({
Name: '',
Tsize: 0,
Hash: cid
})
continue
}
if (Array.isArray(val)) {
findLinks(val, links)
}
if (val && typeof val === 'object') {
findLinks(val, links)
}
}
return links
}
/**
* @param {Object} config
* @param {import('ipfs-repo').IPFSRepo} config.repo
* @param {import('ipfs-core-utils/src/multicodecs')} config.codecs
*/
module.exports = ({ repo, codecs }) => {
/**
* @type {import('ipfs-core-types/src/object').API["links"]}
*/
async function links (cid, options = {}) {
const codec = await codecs.getCodec(cid.code)
const block = await repo.blocks.get(cid, options)
const node = codec.decode(block)
if (cid.code === raw.code) {
return []
}
if (cid.code === dagPb.code) {
return node.Links
}
if (cid.code === dagCbor.code) {
return findLinks(node)
}
throw new Error(`Cannot resolve links from codec ${cid.code}`)
}
return withTimeoutOption(links)
}