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 pathmock-preload-node-utils.js
76 lines (65 loc) · 2.14 KB
/
mock-preload-node-utils.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
/* eslint-env browser */
import { multiaddrToUri } from '@multiformats/multiaddr-to-uri'
import errCode from 'err-code'
import HTTP from 'ipfs-utils/src/http.js'
import { waitFor } from './wait-for.js'
/**
* @typedef {import('multiformats/cid').CID} CID
*/
export const defaultPort = 1138
export const defaultAddr = `/dnsaddr/localhost/tcp/${defaultPort}`
/**
* Get the stored preload CIDs for the server at `addr`
*
* @param {string} [addr]
* @returns {Promise<string[]>}
*/
export async function getPreloadCids (addr) {
const res = await HTTP.get(`${multiaddrToUri(addr || defaultAddr)}/cids`)
return res.json()
}
/**
* Clear the stored preload URLs for the server at `addr`
*
* @param {string} [addr]
*/
export function clearPreloadCids (addr) {
return HTTP.delete(`${multiaddrToUri(addr || defaultAddr)}/cids`)
}
/**
* Wait for the passed CIDs to appear in the CID list from the preload node
*
* @param {CID | CID[] | string | string[]} cids
* @param {object} [opts]
* @param {number} [opts.timeout]
* @param {string} [opts.addr]
*/
export async function waitForCids (cids, opts) {
const options = opts || {}
options.timeout = options.timeout || 1000
const cidArr = Array.isArray(cids) ? cids : [cids]
const cidStrs = cidArr.map(cid => cid.toString()) // Allow passing CID instance
await waitFor(async () => {
const preloadCids = await getPreloadCids(options.addr)
// See if our cached preloadCids includes all the cids we're looking for.
/** @type {{ missing: string[], duplicates: string[] }} */
const results = { missing: [], duplicates: [] }
const { missing, duplicates } = cidStrs.reduce((results, cid) => {
const count = preloadCids.filter(preloadedCid => preloadedCid === cid).length
if (count === 0) {
results.missing.push(cid)
} else if (count > 1) {
results.duplicates.push(cid)
}
return results
}, results)
if (duplicates.length) {
throw errCode(new Error(`Multiple occurrences of ${duplicates} found`), 'ERR_DUPLICATE')
}
return missing.length === 0
}, {
name: 'CIDs to be preloaded',
interval: 5,
timeout: options.timeout
})
}