-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathipfs-check-client.js
55 lines (49 loc) · 1.32 KB
/
ipfs-check-client.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
/* global AbortController */
import fetch from '@web-std/fetch'
/**
* @typedef {{
* ConnectionError: string
* PeerFoundInDHT: Record<string, number>
* CidInDHT: boolean
* DataAvailableOverBitswap: {
* Duration: number
* Found: boolean
* Responded: boolean
* Error: string
* }
* }} IpfsCheckResult
*/
const TIMEOUT = 30_000
export class IpfsCheckClient {
/**
* @param {string} endpoint
* @param {{ timeout?: number }} [options]
*/
constructor (endpoint, options) {
this.endpoint = endpoint
this._options = options || {}
}
/**
* @param {string} cid
* @param {string} multiaddr
*/
async check (cid, multiaddr) {
const url = new URL(this.endpoint)
url.searchParams.set('cid', String(cid))
url.searchParams.set('multiaddr', String(multiaddr))
const controller = new AbortController()
const timeoutMs = this._options.timeout || TIMEOUT
const timeoutId = setTimeout(() => controller.abort(), timeoutMs)
try {
const res = await fetch(url, { method: 'POST', signal: controller.signal })
if (!res.ok) {
throw new Error(`failed to check ${cid} @ ${multiaddr}: ${await res.text()}`)
}
/** @type {IpfsCheckResult} */
const out = await res.json()
return out
} finally {
clearTimeout(timeoutId)
}
}
}