|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const dagPB = require('ipld-dag-pb') |
| 4 | +const dagCBOR = require('ipld-dag-cbor') |
| 5 | +const promisify = require('promisify-es6') |
| 6 | +const CID = require('cids') |
| 7 | +const multihash = require('multihashes') |
| 8 | + |
| 9 | +function noop () {} |
| 10 | + |
| 11 | +module.exports = (send) => { |
| 12 | + const api = { |
| 13 | + put: promisify((dagNode, options, callback) => { |
| 14 | + if (typeof options === 'function') { |
| 15 | + return setImmediate(() => callback(new Error('no options were passed'))) |
| 16 | + } |
| 17 | + |
| 18 | + callback = callback || noop |
| 19 | + |
| 20 | + let hashAlg = options.hashAlg || 'sha2-256' |
| 21 | + let format |
| 22 | + let inputEnc |
| 23 | + |
| 24 | + if (options.cid && CID.isCID(options.cid)) { |
| 25 | + format = options.cid.codec |
| 26 | + hashAlg = multihash.decode(options.cid.multihash).name |
| 27 | + prepare() |
| 28 | + } else if (options.format) { |
| 29 | + format = options.format |
| 30 | + prepare() |
| 31 | + } else { |
| 32 | + callback(new Error('Invalid arguments')) |
| 33 | + } |
| 34 | + |
| 35 | + function prepare () { |
| 36 | + if (format === 'dag-cbor') { |
| 37 | + // TODO change this once |
| 38 | + // https://github.com./ipfs/go-ipfs/issues/3771 is finished |
| 39 | + format = 'cbor' |
| 40 | + |
| 41 | + inputEnc = 'cbor' |
| 42 | + dagCBOR.util.serialize(dagNode, finalize) |
| 43 | + } |
| 44 | + if (format === 'dag-pb') { |
| 45 | + // TODO change this once |
| 46 | + // https://github.com./ipfs/go-ipfs/issues/3771 is finished |
| 47 | + format = 'protobuf' |
| 48 | + |
| 49 | + inputEnc = 'protobuf' |
| 50 | + dagPB.util.serialize(dagNode, finalize) |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + function finalize (err, serialized) { |
| 55 | + if (err) { return callback(err) } |
| 56 | + |
| 57 | + send({ |
| 58 | + path: 'dag/put', |
| 59 | + qs: { |
| 60 | + hashAlg: hashAlg, // not implemented in go yet https://github.com./ipfs/go-ipfs/issues/3771 |
| 61 | + format: format, |
| 62 | + inputenc: inputEnc |
| 63 | + }, |
| 64 | + files: serialized |
| 65 | + }, (err, result) => { |
| 66 | + if (err) { |
| 67 | + return callback(err) |
| 68 | + } |
| 69 | + // TODO handle the result |
| 70 | + }) |
| 71 | + } |
| 72 | + }), |
| 73 | + get: promisify((cid, path, options, callback) => { |
| 74 | + // TODO |
| 75 | + }) |
| 76 | + } |
| 77 | + |
| 78 | + return api |
| 79 | +} |
0 commit comments