This repository was archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathput.js
68 lines (58 loc) · 2.1 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
'use strict'
const CID = require('cids')
const multihash = require('multihashes')
const configure = require('../lib/configure')
const multipartRequest = require('../lib/multipart-request')
const toUrlSearchParams = require('../lib/to-url-search-params')
const { anySignal } = require('any-signal')
const AbortController = require('native-abort-controller')
const multicodec = require('multicodec')
const loadFormat = require('../lib/ipld-formats')
module.exports = configure((api, opts) => {
const load = loadFormat(opts.ipld)
/**
* @type {import('..').Implements<typeof import('ipfs-core/src/components/dag/put')>}
*/
const put = async (dagNode, options = {}) => {
if (options.cid && (options.format || options.hashAlg)) {
throw new Error('Failed to put DAG node. Provide either `cid` OR `format` and `hashAlg` options')
} else if ((options.format && !options.hashAlg) || (!options.format && options.hashAlg)) {
throw new Error('Failed to put DAG node. Provide `format` AND `hashAlg` options')
}
let encodingOptions
if (options.cid) {
const cid = new CID(options.cid)
encodingOptions = {
...options,
// @ts-expect-error - https://github.com/multiformats/js-cid/pull/138
format: multicodec.getName(cid.code),
hashAlg: multihash.decode(cid.multihash).name
}
delete options.cid
} else {
encodingOptions = options
}
const settings = {
format: 'dag-cbor',
hashAlg: 'sha2-256',
inputEnc: 'raw',
...encodingOptions
}
const format = await load(settings.format)
const serialized = format.util.serialize(dagNode)
// allow aborting requests on body errors
const controller = new AbortController()
const signal = anySignal([controller.signal, settings.signal])
const res = await api.post('dag/put', {
timeout: settings.timeout,
signal,
searchParams: toUrlSearchParams(settings),
...(
await multipartRequest(serialized, controller, settings.headers)
)
})
const data = await res.json()
return new CID(data.Cid['/'])
}
return put
})