forked from ipfs-inactive/js-ipfs-http-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathput.js
83 lines (70 loc) · 2.21 KB
/
put.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
'use strict'
const dagPB = require('ipld-dag-pb')
const dagCBOR = require('ipld-dag-cbor')
const promisify = require('promisify-es6')
const CID = require('cids')
const multihash = require('multihashes')
const SendOneFile = require('../utils/send-one-file')
module.exports = (send) => {
const sendOneFile = SendOneFile(send, 'dag/put')
return promisify((dagNode, options, callback) => {
if (typeof options === 'function') {
callback = options
}
options = options || {}
if (options.hash) {
options.hashAlg = options.hash
delete options.hash
}
if (options.cid && (options.format || options.hashAlg)) {
return callback(new Error('Can\'t put dag node. Please provide either `cid` OR `format` and `hash` options.'))
} else if ((options.format && !options.hashAlg) || (!options.format && options.hashAlg)) {
return callback(new Error('Can\'t put dag node. Please provide `format` AND `hash` options.'))
}
if (options.cid) {
let cid
try {
cid = new CID(options.cid)
} catch (err) {
return callback(err)
}
options.format = cid.codec
options.hashAlg = multihash.decode(cid.multihash).name
delete options.cid
}
const optionDefaults = {
format: 'dag-cbor',
hashAlg: 'sha2-256',
inputEnc: 'raw'
}
options = Object.assign(optionDefaults, options)
if (options.format === 'dag-cbor') {
dagCBOR.util.serialize(dagNode, finalize)
} else if (options.format === 'dag-pb') {
dagPB.util.serialize(dagNode, finalize)
} else {
// FIXME Hopefully already serialized...can we use IPLD to serialise instead?
finalize(null, dagNode)
}
function finalize (err, serialized) {
if (err) { return callback(err) }
const sendOptions = {
qs: {
hash: options.hashAlg,
format: options.format,
'input-enc': options.inputEnc
}
}
sendOneFile(serialized, sendOptions, (err, result) => {
if (err) {
return callback(err)
}
if (result['Cid']) {
return callback(null, new CID(result['Cid']['/']))
} else {
return callback(result)
}
})
}
})
}