diff --git a/src/util.js b/src/util.js index 290cbc8..dd9e8ec 100644 --- a/src/util.js +++ b/src/util.js @@ -69,7 +69,25 @@ exports.deserialize = (data, callback) => { } } -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] - Ignored + * @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 || {} waterfall([ (cb) => exports.serialize(dagNode, cb), (serialized, cb) => multihashing(serialized, resolver.defaultHashAlg, cb), diff --git a/test/util.spec.js b/test/util.spec.js new file mode 100644 index 0000000..8f70fd6 --- /dev/null +++ b/test/util.spec.js @@ -0,0 +1,61 @@ +/* eslint-env mocha */ +'use strict' + +const chai = require('chai') +const dirtyChai = require('dirty-chai') +const expect = chai.expect +chai.use(dirtyChai) +const ipldGit = require('../src') +const multihash = require('multihashes') +const CID = require('cids') + +describe('IPLD format util', () => { + const tagNode = { + gitType: 'tag', + object: {'/': new CID('z8mWaHQaEAKd5KMRNU3npB3saSZmhFh3e').buffer}, + type: 'commit', + tag: 'v0.0.0', + tagger: { + name: 'John Doe', + email: 'johndoe@example.com', + date: '1497302532 +0200' + }, + message: 'A message\n' + } + + it('.serialize and .deserialize', (done) => { + ipldGit.util.serialize(tagNode, (err, serialized) => { + expect(err).to.not.exist() + expect(Buffer.isBuffer(serialized)).to.equal(true) + ipldGit.util.deserialize(serialized, (err, deserialized) => { + expect(err).to.not.exist() + expect(tagNode).to.eql(deserialized) + done() + }) + }) + }) + + it('.cid', (done) => { + ipldGit.util.cid(tagNode, (err, cid) => { + expect(err).to.not.exist() + expect(cid.version).to.equal(1) + expect(cid.codec).to.equal('git-raw') + expect(cid.multihash).to.exist() + const mh = multihash.decode(cid.multihash) + expect(mh.name).to.equal('sha1') + done() + }) + }) + + it('.cid ignores options', (done) => { + ipldGit.util.cid(tagNode, { hashAlg: 'unknown' }, (err, cid) => { + expect(err).to.not.exist() + expect(cid.version).to.equal(1) + expect(cid.codec).to.equal('git-raw') + expect(cid.multihash).to.exist() + const mh = multihash.decode(cid.multihash) + expect(mh.name).to.equal('sha1') + done() + }) + }) +})