Skip to content

Commit

Permalink
fix(validator): Allow form data will mutliple values appended (honojs…
Browse files Browse the repository at this point in the history
  • Loading branch information
nicksrandall authored Aug 17, 2024
1 parent 81a1f07 commit 0c1e899
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
15 changes: 15 additions & 0 deletions src/validator/validator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
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)
} else if (key in form) {
form[key] = [form[key] as string | File, value]
} else {
form[key] = value
}
Expand Down

0 comments on commit 0c1e899

Please sign in to comment.