mirror of
https://github.com/versia-pub/api.git
synced 2025-12-06 08:28:19 +01:00
fix(client): 🐛 Fix formData converter to work on nested arrays
This commit is contained in:
parent
7aec850390
commit
8094760aad
|
|
@ -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(),
|
||||||
return formData;
|
parentKey = "",
|
||||||
}
|
): FormData => {
|
||||||
if (obj[key] instanceof File) {
|
if (obj === undefined || obj === null) {
|
||||||
formData.append(key, obj[key] as Blob);
|
|
||||||
return formData;
|
|
||||||
}
|
|
||||||
if (Array.isArray(obj[key])) {
|
|
||||||
(obj[key] as ConvertibleObject[]).forEach((item, index) => {
|
|
||||||
if (item instanceof File) {
|
|
||||||
formData.append(`${key}[${index}]`, item as Blob);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
formData.append(`${key}[${index}]`, String(item));
|
|
||||||
});
|
|
||||||
|
|
||||||
return formData;
|
|
||||||
}
|
|
||||||
if (typeof obj[key] === "object") {
|
|
||||||
const nested = objectToFormData(obj[key] as ConvertibleObject);
|
|
||||||
|
|
||||||
for (const [nestedKey, value] of nested.entries()) {
|
|
||||||
formData.append(`${key}[${nestedKey}]`, value);
|
|
||||||
}
|
|
||||||
|
|
||||||
return formData;
|
|
||||||
}
|
|
||||||
formData.append(key, String(obj[key]));
|
|
||||||
return formData;
|
return formData;
|
||||||
}, new FormData());
|
}
|
||||||
|
|
||||||
|
for (const key of Object.keys(obj)) {
|
||||||
|
const value = obj[key];
|
||||||
|
const fullKey = parentKey ? `${parentKey}[${key}]` : key;
|
||||||
|
|
||||||
|
if (value === undefined || value === null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
formData.append(arrayKey, item as Blob);
|
||||||
|
} else if (typeof item === "object") {
|
||||||
|
objectToFormData(
|
||||||
|
item as ConvertibleObject,
|
||||||
|
formData,
|
||||||
|
arrayKey,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
formData.append(arrayKey, String(item));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (typeof value === "object") {
|
||||||
|
objectToFormData(value as ConvertibleObject, formData, fullKey);
|
||||||
|
} else {
|
||||||
|
formData.append(fullKey, String(value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return formData;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue