-
Notifications
You must be signed in to change notification settings - Fork 168
Expand file tree
/
Copy pathipfs.js
More file actions
53 lines (51 loc) · 1.37 KB
/
ipfs.js
File metadata and controls
53 lines (51 loc) · 1.37 KB
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
import { URL } from 'url'
import fetch from '@web-std/fetch'
import assert from 'assert'
import { hasOwnProperty } from './utils'
export class IPFS {
/**
* @param {string|URL} url
* @param {{ headers?: Record<string, string> }} [options]
*/
constructor(url, options = {}) {
this.url = url
this.headers = options.headers || {}
}
/**
* @param {string} cid
* @param {{ timeout?: number }} [options]
*/
async dagSize(cid, options = {}) {
const url = new URL(
`dag/stat?arg=${encodeURIComponent(cid)}&progress=false`,
this.url
)
const controller = new AbortController()
const abortID = setTimeout(
() => controller.abort(),
options.timeout || 60000
)
try {
const response = await fetch(url.toString(), {
headers: this.headers,
signal: controller.signal,
})
if (!response.ok) {
throw Object.assign(
new Error(`${response.status}: ${response.statusText}`),
{ response }
)
}
const data = /** @type {unknown} */ (await response.json())
assert.ok(hasOwnProperty(data, 'Size'))
assert.ok(typeof data.Size === 'string')
const size = parseInt(data.Size)
if (isNaN(size)) {
throw new Error(`invalid DAG size for ${cid}: ${data.Size}`)
}
return size
} finally {
clearTimeout(abortID)
}
}
}