|
3 | 3 | const promisify = require('promisify-es6') |
4 | 4 | const Block = require('ipfs-block') |
5 | 5 | const CID = require('cids') |
6 | | -const once = require('once') |
| 6 | +const multihash = require('multihashes') |
7 | 7 | const SendOneFile = require('../utils/send-one-file') |
8 | 8 |
|
9 | 9 | module.exports = (send) => { |
10 | 10 | const sendOneFile = SendOneFile(send, 'block/put') |
11 | 11 |
|
12 | | - return promisify((block, cid, _callback) => { |
13 | | - // TODO this needs to be adjusted with the new go-ipfs http-api |
14 | | - if (typeof cid === 'function') { |
15 | | - _callback = cid |
16 | | - cid = {} |
| 12 | + return promisify((block, options, callback) => { |
| 13 | + if (typeof options === 'function') { |
| 14 | + callback = options |
| 15 | + options = {} |
17 | 16 | } |
18 | 17 |
|
19 | | - const callback = once(_callback) |
| 18 | + options = options || {} |
20 | 19 |
|
21 | 20 | if (Array.isArray(block)) { |
22 | 21 | return callback(new Error('block.put accepts only one block')) |
23 | 22 | } |
24 | 23 |
|
25 | | - if (typeof block === 'object' && block.data) { |
26 | | - block = block.data |
| 24 | + if (Buffer.isBuffer(block)) { |
| 25 | + block = { data: block } |
27 | 26 | } |
28 | 27 |
|
29 | | - sendOneFile(block, {}, (err, result) => { |
| 28 | + if (!block || !block.data) { |
| 29 | + return callback(new Error('invalid block arg')) |
| 30 | + } |
| 31 | + |
| 32 | + const qs = {} |
| 33 | + |
| 34 | + if (block.cid || options.cid) { |
| 35 | + let cid |
| 36 | + |
| 37 | + try { |
| 38 | + cid = new CID(block.cid || options.cid) |
| 39 | + } catch (err) { |
| 40 | + return callback(err) |
| 41 | + } |
| 42 | + |
| 43 | + const { name, length } = multihash.decode(cid.multihash) |
| 44 | + |
| 45 | + qs.format = cid.codec |
| 46 | + qs.mhtype = name |
| 47 | + qs.mhlen = length |
| 48 | + qs.version = cid.version |
| 49 | + } else { |
| 50 | + if (options.format) qs.format = options.format |
| 51 | + if (options.mhtype) qs.mhtype = options.mhtype |
| 52 | + if (options.mhlen) qs.mhlen = options.mhlen |
| 53 | + if (options.version != null) qs.version = options.version |
| 54 | + } |
| 55 | + |
| 56 | + sendOneFile(block.data, { qs }, (err, result) => { |
30 | 57 | if (err) { |
31 | | - return callback(err) // early |
| 58 | + // Retry with "protobuf" format for go-ipfs |
| 59 | + // TODO: remove when https://github.com/ipfs/go-cid/issues/75 resolved |
| 60 | + if (qs.format === 'dag-pb') { |
| 61 | + qs.format = 'protobuf' |
| 62 | + return sendOneFile(block.data, { qs }, (err, result) => { |
| 63 | + if (err) return callback(err) |
| 64 | + callback(null, new Block(block.data, new CID(result.Key))) |
| 65 | + }) |
| 66 | + } |
| 67 | + |
| 68 | + return callback(err) |
32 | 69 | } |
33 | 70 |
|
34 | | - callback(null, new Block(block, new CID(result.Key))) |
| 71 | + callback(null, new Block(block.data, new CID(result.Key))) |
35 | 72 | }) |
36 | 73 | }) |
37 | 74 | } |
0 commit comments