Skip to content
This repository was archived by the owner on Aug 11, 2021. It is now read-only.

Commit 1aed60e

Browse files
feat: add util.cid options (#66)
See ipld/interface-ipld-format#40
1 parent e095ef5 commit 1aed60e

2 files changed

Lines changed: 40 additions & 3 deletions

File tree

src/util.js

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -108,10 +108,32 @@ exports.deserialize = (data, callback) => {
108108
setImmediate(() => callback(null, deserialized))
109109
}
110110

111-
exports.cid = (dagNode, callback) => {
111+
/**
112+
* @callback CidCallback
113+
* @param {?Error} error - Error if getting the CID failed
114+
* @param {?CID} cid - CID if call was successful
115+
*/
116+
/**
117+
* Get the CID of the DAG-Node.
118+
*
119+
* @param {Object} dagNode - Internal representation
120+
* @param {Object} [options] - Options to create the CID
121+
* @param {number} [options.version=1] - CID version number
122+
* @param {string} [options.hashAlg] - Defaults to hashAlg for the resolver
123+
* @param {CidCallback} callback - Callback that handles the return value
124+
* @returns {void}
125+
*/
126+
exports.cid = (dagNode, options, callback) => {
127+
if (typeof options === 'function') {
128+
callback = options
129+
options = {}
130+
}
131+
options = options || {}
132+
const hashAlg = options.hashAlg || resolver.defaultHashAlg
133+
const version = typeof options.version === 'undefined' ? 1 : options.version
112134
waterfall([
113135
(cb) => exports.serialize(dagNode, cb),
114-
(serialized, cb) => multihashing(serialized, resolver.defaultHashAlg, cb),
115-
(mh, cb) => cb(null, new CID(1, resolver.multicodec, mh))
136+
(serialized, cb) => multihashing(serialized, hashAlg, cb),
137+
(mh, cb) => cb(null, new CID(version, resolver.multicodec, mh))
116138
], callback)
117139
}

test/util.spec.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ chai.use(dirtyChai)
88
const garbage = require('garbage')
99
const map = require('async/map')
1010
const dagCBOR = require('../src')
11+
const multihash = require('multihashes')
1112

1213
describe('util', () => {
1314
const obj = {
@@ -58,6 +59,20 @@ describe('util', () => {
5859
expect(cid.version).to.equal(1)
5960
expect(cid.codec).to.equal('dag-cbor')
6061
expect(cid.multihash).to.exist()
62+
const mh = multihash.decode(cid.multihash)
63+
expect(mh.name).to.equal('sha2-256')
64+
done()
65+
})
66+
})
67+
68+
it('.cid with hashAlg', (done) => {
69+
dagCBOR.util.cid(obj, { hashAlg: 'sha2-512' }, (err, cid) => {
70+
expect(err).to.not.exist()
71+
expect(cid.version).to.equal(1)
72+
expect(cid.codec).to.equal('dag-cbor')
73+
expect(cid.multihash).to.exist()
74+
const mh = multihash.decode(cid.multihash)
75+
expect(mh.name).to.equal('sha2-512')
6176
done()
6277
})
6378
})

0 commit comments

Comments
 (0)