-
Notifications
You must be signed in to change notification settings - Fork 485
/
Copy pathformData.ts
62 lines (54 loc) · 1.81 KB
/
formData.ts
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
import { FormDataConvertible, SerializationArrayFormat } from './types'
export function objectToFormData(
source: Record<string, FormDataConvertible>,
form: FormData,
parentKey: string | null,
formDataArrayFormat: SerializationArrayFormat,
): FormData {
source = source || {}
for (const key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
append(form, composeObjectKey(parentKey, key), source[key], formDataArrayFormat)
}
}
return form
}
function composeKey(parent: string | null, key: string, format: SerializationArrayFormat): string {
if (!parent) return key
switch (format) {
case 'indices':
return `${parent}[${key}]`
case 'brackets':
return `${parent}[]`
}
}
function composeObjectKey(parent: string | null, key: string): string {
return composeKey(parent, key, 'indices')
}
function append(
form: FormData,
key: string,
value: FormDataConvertible,
formDataArrayFormat: SerializationArrayFormat,
): void {
if (Array.isArray(value)) {
return Array.from(value.keys()).forEach((index) =>
append(form, composeKey(key, index.toString(), formDataArrayFormat), value[index], formDataArrayFormat),
)
} else if (value instanceof Date) {
return form.append(key, value.toISOString())
} else if (value instanceof File) {
return form.append(key, value, value.name)
} else if (value instanceof Blob) {
return form.append(key, value)
} else if (typeof value === 'boolean') {
return form.append(key, value ? '1' : '0')
} else if (typeof value === 'string') {
return form.append(key, value)
} else if (typeof value === 'number') {
return form.append(key, `${value}`)
} else if (value === null || value === undefined) {
return form.append(key, '')
}
objectToFormData(value, form, key, formDataArrayFormat)
}