From 0c1e89964ee3d40ac0c0167858f0ec35eb1b6ebf Mon Sep 17 00:00:00 2001 From: Nick Randall Date: Sat, 17 Aug 2024 02:55:40 -0700 Subject: [PATCH] fix(validator): Allow form data will mutliple values appended (#3273) --- src/validator/validator.test.ts | 15 +++++++++++++++ src/validator/validator.ts | 10 +++++----- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/validator/validator.test.ts b/src/validator/validator.test.ts index cc3b6d957..aad7785bb 100644 --- a/src/validator/validator.test.ts +++ b/src/validator/validator.test.ts @@ -260,6 +260,21 @@ describe('FormData', () => { 'foo[]': ['bar1', 'bar2'], }) }) + + it('Should return `foo` as an array if multiple values are appended', async () => { + const form = new FormData() + form.append('foo', 'bar1') + form.append('foo', 'bar2') + form.append('foo', 'bar3') + const res = await app.request('/post', { + method: 'POST', + body: form, + }) + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ + foo: ['bar1', 'bar2', 'bar3'], + }) + }) }) describe('Malformed FormData request', () => { diff --git a/src/validator/validator.ts b/src/validator/validator.ts index a99117f8f..68ddabd2d 100644 --- a/src/validator/validator.ts +++ b/src/validator/validator.ts @@ -108,11 +108,11 @@ export const validator = < const form: BodyData<{ all: true }> = {} formData.forEach((value, key) => { if (key.endsWith('[]')) { - if (form[key] === undefined) { - form[key] = [value] - } else if (Array.isArray(form[key])) { - ;(form[key] as unknown[]).push(value) - } + ;((form[key] ??= []) as unknown[]).push(value) + } else if (Array.isArray(form[key])) { + ;(form[key] as unknown[]).push(value) + } else if (key in form) { + form[key] = [form[key] as string | File, value] } else { form[key] = value }