Skip to content

Commit

Permalink
fix(validator): Allow form data will mutliple values appended
Browse files Browse the repository at this point in the history
  • Loading branch information
nicksrandall committed Aug 15, 2024
1 parent 986db29 commit c622964
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
14 changes: 14 additions & 0 deletions src/validator/validator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,20 @@ 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')
const res = await app.request('/post', {
method: 'POST',
body: form,
})
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
foo: ['bar1', 'bar2'],
})
})
})

describe('Malformed FormData request', () => {
Expand Down
10 changes: 5 additions & 5 deletions src/validator/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Check warning on line 113 in src/validator/validator.ts

View check run for this annotation

Codecov / codecov/patch

src/validator/validator.ts#L113

Added line #L113 was not covered by tests
} else if (key in form) {
form[key] = [form[key] as string | File, value]
} else {
form[key] = value
}
Expand Down

0 comments on commit c622964

Please sign in to comment.