-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·44 lines (36 loc) · 1.09 KB
/
index.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
const HeliaUnixFS = import('@helia/unixfs');
const Helia = import('helia');
const Multiformats = import('multiformats/cid');
const ipfs = Helia.then(async ({createHelia}) =>
(await HeliaUnixFS).unixfs(await createHelia())
);
const ipfsFetch = async (hash, {timeout} = {}) => {
timeout =
typeof timeout === 'number' && !isNaN(timeout) && timeout > 0 ?
timeout :
undefined;
const result = (async () => {
const iter = (await ipfs).cat(
(await Multiformats).CID.parse(hash),
timeout !== undefined && typeof AbortSignal !== 'undefined' ?
{signal: AbortSignal.timeout(timeout)} :
undefined
);
const buffers = [];
for await (const buf of iter) {
buffers.push(buf);
}
return Buffer.concat(buffers);
})();
if (timeout === undefined || typeof AbortSignal !== 'undefined') {
return result;
}
const timeoutPromise = new Promise(resolve => {
setTimeout(resolve, timeout);
}).then(() => {
throw new Error(`Timeout of ${timeout.toString()} exceeded.`);
});
return Promise.race([result, timeoutPromise]);
};
module.exports = ipfsFetch;
module.exports.ipfsFetch = ipfsFetch;