From 8094760aadd4c182c70fe16449837b311a62e805 Mon Sep 17 00:00:00 2001 From: Jesse Wierzbinski Date: Sat, 7 Dec 2024 17:14:38 +0100 Subject: [PATCH] fix(client): :bug: Fix formData converter to work on nested arrays --- client/versia/base.ts | 64 +++++++++++++++++++++++++------------------ 1 file changed, 37 insertions(+), 27 deletions(-) diff --git a/client/versia/base.ts b/client/versia/base.ts index 2e196dd..2c000f8 100644 --- a/client/versia/base.ts +++ b/client/versia/base.ts @@ -23,38 +23,48 @@ export interface Output { 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; }; /**