fix(client): 🐛 Fix formData converter to work on nested arrays

This commit is contained in:
Jesse Wierzbinski 2024-12-07 17:14:38 +01:00
parent 7aec850390
commit 8094760aad
No known key found for this signature in database

View file

@ -23,38 +23,48 @@ export interface Output<ReturnType> {
raw: Response; raw: Response;
} }
const objectToFormData = (obj: ConvertibleObject): FormData => { const objectToFormData = (
return Object.keys(obj).reduce((formData, key) => { obj: ConvertibleObject,
if (obj[key] === undefined || obj[key] === null) { formData = new FormData(),
parentKey = "",
): FormData => {
if (obj === undefined || obj === null) {
return formData; return formData;
} }
if (obj[key] instanceof File) {
formData.append(key, obj[key] as Blob); for (const key of Object.keys(obj)) {
return formData; const value = obj[key];
const fullKey = parentKey ? `${parentKey}[${key}]` : key;
if (value === undefined || value === null) {
continue;
} }
if (Array.isArray(obj[key])) {
(obj[key] as ConvertibleObject[]).forEach((item, index) => { if (value instanceof File) {
formData.append(fullKey, value as Blob);
} else if (Array.isArray(value)) {
for (const [index, item] of value.entries()) {
const arrayKey = `${fullKey}[${index}]`;
if (item instanceof File) { if (item instanceof File) {
formData.append(`${key}[${index}]`, item as Blob); formData.append(arrayKey, item as Blob);
return; } else if (typeof item === "object") {
objectToFormData(
item as ConvertibleObject,
formData,
arrayKey,
);
} else {
formData.append(arrayKey, String(item));
} }
formData.append(`${key}[${index}]`, String(item));
});
return formData;
} }
if (typeof obj[key] === "object") { } else if (typeof value === "object") {
const nested = objectToFormData(obj[key] as ConvertibleObject); objectToFormData(value as ConvertibleObject, formData, fullKey);
} else {
for (const [nestedKey, value] of nested.entries()) { formData.append(fullKey, String(value));
formData.append(`${key}[${nestedKey}]`, value); }
} }
return formData; return formData;
}
formData.append(key, String(obj[key]));
return formData;
}, new FormData());
}; };
/** /**