This repository has been 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
/
resolve.js
87 lines (70 loc) · 2.18 KB
/
resolve.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
'use strict'
const promisify = require('promisify-es6')
const isIpfs = require('is-ipfs')
const setImmediate = require('async/setImmediate')
const doUntil = require('async/doUntil')
const CID = require('cids')
const { cidToString } = require('../../utils/cid')
module.exports = (self) => {
return promisify((name, opts, cb) => {
if (typeof opts === 'function') {
cb = opts
opts = {}
}
opts = opts || {}
if (!isIpfs.path(name)) {
return setImmediate(() => cb(new Error('invalid argument')))
}
// TODO remove this and update subsequent code when IPNS is implemented
if (!isIpfs.ipfsPath(name)) {
return setImmediate(() => cb(new Error('resolve non-IPFS names is not implemented')))
}
const split = name.split('/') // ['', 'ipfs', 'hash', ...path]
const cid = new CID(split[2])
if (split.length === 3) {
return setImmediate(() => cb(null, `/ipfs/${cidToString(cid, { base: opts.cidBase })}`))
}
const path = split.slice(3).join('/')
resolve(cid, path, (err, cid) => {
if (err) return cb(err)
if (!cid) return cb(new Error('found non-link at given path'))
cb(null, `/ipfs/${cidToString(cid, { base: opts.cidBase })}`)
})
})
// Resolve the given CID + path to a CID.
function resolve (cid, path, callback) {
let value
doUntil(
(cb) => {
self.block.get(cid, (err, block) => {
if (err) return cb(err)
const r = self._ipld.resolvers[cid.codec]
if (!r) {
return cb(new Error(`No resolver found for codec "${cid.codec}"`))
}
r.resolver.resolve(block.data, path, (err, result) => {
if (err) return cb(err)
value = result.value
path = result.remainderPath
cb()
})
})
},
() => {
const endReached = !path || path === '/'
if (endReached) {
return true
}
if (value) {
cid = new CID(value['/'])
}
return false
},
(err) => {
if (err) return callback(err)
if (value && value['/']) return callback(null, new CID(value['/']))
callback()
}
)
}
}