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 pathmultipart-request.browser.js
71 lines (57 loc) · 1.75 KB
/
multipart-request.browser.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
// Import browser version otherwise electron-renderer will end up with node
// version and fail.
import { normaliseInput } from './files/normalise-input-multiple.browser.js'
import { modeToString } from './mode-to-string.js'
/**
* @typedef {import('ipfs-core-types/src/utils').ImportCandidateStream} ImportCandidateStream
*/
/**
* @param {ImportCandidateStream} source
* @param {AbortController} abortController
* @param {Headers|Record<string, string>} [headers]
*/
export async function multipartRequest (source, abortController, headers = {}) {
const parts = []
const formData = new FormData()
let index = 0
let total = 0
for await (const { content, path, mode, mtime } of normaliseInput(source)) {
let fileSuffix = ''
const type = content ? 'file' : 'dir'
if (index > 0) {
fileSuffix = `-${index}`
}
let fieldName = type + fileSuffix
const qs = []
if (mode !== null && mode !== undefined) {
qs.push(`mode=${modeToString(mode)}`)
}
if ((mtime) != null) {
const { secs, nsecs } = (mtime)
qs.push(`mtime=${secs}`)
if (nsecs != null) {
qs.push(`mtime-nsecs=${nsecs}`)
}
}
if (qs.length) {
fieldName = `${fieldName}?${qs.join('&')}`
}
if (content) {
formData.set(fieldName, content, path != null ? encodeURIComponent(path) : undefined)
const end = total + content.size
parts.push({ name: path, start: total, end })
total = end
} else if (path != null) {
formData.set(fieldName, new File([''], encodeURIComponent(path), { type: 'application/x-directory' }))
} else {
throw new Error('path or content or both must be set')
}
index++
}
return {
total,
parts,
headers,
body: formData
}
}