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 pathipld-formats.js
58 lines (48 loc) · 1.51 KB
/
ipld-formats.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
'use strict'
const dagPB = require('ipld-dag-pb')
const dagCBOR = require('ipld-dag-cbor')
const raw = require('ipld-raw')
const multicodec = require('multicodec')
const noop = () => {}
/**
* @typedef {import('cids')} CID
*/
/**
* Return an object containing supported IPLD Formats
*
* @param {object} [options] - IPLD options passed to the http client constructor
* @param {Array} [options.formats] - A list of IPLD Formats to use
* @param {Function} [options.loadFormat] - An async function that can load a format when passed a codec number
* @returns {Function}
*/
module.exports = ({ formats = [], loadFormat = noop } = {}) => {
formats = formats || []
loadFormat = loadFormat || noop
const configuredFormats = {
[multicodec.DAG_PB]: dagPB,
[multicodec.DAG_CBOR]: dagCBOR,
[multicodec.RAW]: raw
}
formats.forEach(format => {
configuredFormats[format.codec] = format
})
/**
* Attempts to load an IPLD format for the passed CID
*
* @param {import('multicodec').CodecName} codec - The code to load the format for
* @returns {Promise<object>} - An IPLD format
*/
const loadResolver = async (codec) => {
// @ts-ignore - codec is a string and not a CodecName
const number = multicodec.getNumber(codec)
const format = configuredFormats[number] || await loadFormat(codec)
if (!format) {
throw Object.assign(
new Error(`Missing IPLD format "${codec}"`),
{ missingMulticodec: codec }
)
}
return format
}
return loadResolver
}