Skip to content

Commit

Permalink
fix(client): 🐛 Fix formData converter to work on nested arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
CPlusPatch committed Dec 7, 2024
1 parent 7aec850 commit 8094760
Showing 1 changed file with 37 additions and 27 deletions.
64 changes: 37 additions & 27 deletions client/versia/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,38 +23,48 @@ export interface Output<ReturnType> {
raw: Response;
}

const objectToFormData = (obj: ConvertibleObject): FormData => {
return Object.keys(obj).reduce((formData, key) => {
if (obj[key] === undefined || obj[key] === null) {
return formData;
}
if (obj[key] instanceof File) {
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));
});
const objectToFormData = (
obj: ConvertibleObject,
formData = new FormData(),
parentKey = "",
): FormData => {
if (obj === undefined || obj === null) {
return formData;
}

for (const key of Object.keys(obj)) {
const value = obj[key];
const fullKey = parentKey ? `${parentKey}[${key}]` : key;

return formData;
if (value === undefined || value === null) {
continue;
}
if (typeof obj[key] === "object") {
const nested = objectToFormData(obj[key] as ConvertibleObject);

for (const [nestedKey, value] of nested.entries()) {
formData.append(`${key}[${nestedKey}]`, value);
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));
}
}

return formData;
} else if (typeof value === "object") {
objectToFormData(value as ConvertibleObject, formData, fullKey);
} else {
formData.append(fullKey, String(value));
}
formData.append(key, String(obj[key]));
return formData;
}, new FormData());
}

return formData;
};

/**
Expand Down

0 comments on commit 8094760

Please sign in to comment.