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.js
69 lines (54 loc) · 1.88 KB
/
multipart-request.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
'use strict'
const normaliseInput = require('ipfs-core-utils/src/files/normalise-input')
const toStream = require('./to-stream')
const { nanoid } = require('nanoid')
const modeToString = require('../lib/mode-to-string')
const mtimeToObject = require('../lib/mtime-to-object')
const merge = require('merge-options').bind({ ignoreUndefined: true })
async function multipartRequest (source = '', abortController, headers = {}, boundary = `-----------------------------${nanoid()}`) {
async function * streamFiles (source) {
try {
let index = 0
for await (const { content, path, mode, mtime } of normaliseInput(source)) {
let fileSuffix = ''
const type = content ? 'file' : 'dir'
if (index > 0) {
yield '\r\n'
fileSuffix = `-${index}`
}
yield `--${boundary}\r\n`
yield `Content-Disposition: form-data; name="${type}${fileSuffix}"; filename="${encodeURIComponent(path)}"\r\n`
yield `Content-Type: ${content ? 'application/octet-stream' : 'application/x-directory'}\r\n`
if (mode !== null && mode !== undefined) {
yield `mode: ${modeToString(mode)}\r\n`
}
if (mtime != null) {
const {
secs, nsecs
} = mtimeToObject(mtime)
yield `mtime: ${secs}\r\n`
if (nsecs != null) {
yield `mtime-nsecs: ${nsecs}\r\n`
}
}
yield '\r\n'
if (content) {
yield * content
}
index++
}
} catch (err) {
// workaround for https://github.com/node-fetch/node-fetch/issues/753
abortController.abort(err)
} finally {
yield `\r\n--${boundary}--\r\n`
}
}
return {
headers: merge(headers, {
'Content-Type': `multipart/form-data; boundary=${boundary}`
}),
body: await toStream(streamFiles(source))
}
}
module.exports = multipartRequest