From 1aed60e5d67735e08be329485851ddda907eb505 Mon Sep 17 00:00:00 2001 From: Richard Schneider Date: Mon, 25 Jun 2018 20:10:39 +1200 Subject: [PATCH] feat: add util.cid options (#66) See https://github.com/ipld/interface-ipld-format/issues/40 --- src/util.js | 28 +++++++++++++++++++++++++--- test/util.spec.js | 15 +++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/src/util.js b/src/util.js index 84765bc..f039dd3 100644 --- a/src/util.js +++ b/src/util.js @@ -108,10 +108,32 @@ exports.deserialize = (data, callback) => { setImmediate(() => callback(null, deserialized)) } -exports.cid = (dagNode, callback) => { +/** + * @callback CidCallback + * @param {?Error} error - Error if getting the CID failed + * @param {?CID} cid - CID if call was successful + */ +/** + * Get the CID of the DAG-Node. + * + * @param {Object} dagNode - Internal representation + * @param {Object} [options] - Options to create the CID + * @param {number} [options.version=1] - CID version number + * @param {string} [options.hashAlg] - Defaults to hashAlg for the resolver + * @param {CidCallback} callback - Callback that handles the return value + * @returns {void} + */ +exports.cid = (dagNode, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + options = options || {} + const hashAlg = options.hashAlg || resolver.defaultHashAlg + const version = typeof options.version === 'undefined' ? 1 : options.version waterfall([ (cb) => exports.serialize(dagNode, cb), - (serialized, cb) => multihashing(serialized, resolver.defaultHashAlg, cb), - (mh, cb) => cb(null, new CID(1, resolver.multicodec, mh)) + (serialized, cb) => multihashing(serialized, hashAlg, cb), + (mh, cb) => cb(null, new CID(version, resolver.multicodec, mh)) ], callback) } diff --git a/test/util.spec.js b/test/util.spec.js index 0fe6e17..3e01c45 100644 --- a/test/util.spec.js +++ b/test/util.spec.js @@ -8,6 +8,7 @@ chai.use(dirtyChai) const garbage = require('garbage') const map = require('async/map') const dagCBOR = require('../src') +const multihash = require('multihashes') describe('util', () => { const obj = { @@ -58,6 +59,20 @@ describe('util', () => { expect(cid.version).to.equal(1) expect(cid.codec).to.equal('dag-cbor') expect(cid.multihash).to.exist() + const mh = multihash.decode(cid.multihash) + expect(mh.name).to.equal('sha2-256') + done() + }) + }) + + it('.cid with hashAlg', (done) => { + dagCBOR.util.cid(obj, { hashAlg: 'sha2-512' }, (err, cid) => { + expect(err).to.not.exist() + expect(cid.version).to.equal(1) + expect(cid.codec).to.equal('dag-cbor') + expect(cid.multihash).to.exist() + const mh = multihash.decode(cid.multihash) + expect(mh.name).to.equal('sha2-512') done() }) })