Skip to content

Commit

Permalink
fix(validator): form supports multiple values with foo[] (#2639)
Browse files Browse the repository at this point in the history
* fix(validator): `form` supports multiple values `foo[]`

* denoify
  • Loading branch information
yusukebe committed May 8, 2024
1 parent 413c936 commit 799a8d8
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 2 deletions.
10 changes: 9 additions & 1 deletion deno_dist/validator/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,15 @@ export const validator = <
const formData = await bufferToFormData(arrayBuffer, contentType)
const form: BodyData = {}
formData.forEach((value, key) => {
form[key] = value
if (key.endsWith('[]')) {
if (form[key] === undefined) {
form[key] = [value]
} else if (Array.isArray(form[key])) {
;(form[key] as unknown[]).push(value)
}
} else {
form[key] = value
}
})
value = form
c.req.bodyCache.formData = formData
Expand Down
27 changes: 27 additions & 0 deletions src/validator/validator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,33 @@ describe('Cached contents', () => {
})
})

describe('Form with multiple values', () => {
const app = new Hono()

app.post(
'/',
validator('form', (value) => value),
async (c) => {
const data = c.req.valid('form')
return c.json(data)
}
)

it('Should return `foo[]` as an array', async () => {
const form = new FormData()
form.append('foo[]', 'bar1')
form.append('foo[]', 'bar2')
const res = await app.request('/', {
method: 'POST',
body: form,
})
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
'foo[]': ['bar1', 'bar2'],
})
})
})

describe('Validator middleware with a custom validation function', () => {
const app = new Hono()

Expand Down
10 changes: 9 additions & 1 deletion src/validator/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,15 @@ export const validator = <
const formData = await bufferToFormData(arrayBuffer, contentType)
const form: BodyData = {}
formData.forEach((value, key) => {
form[key] = value
if (key.endsWith('[]')) {
if (form[key] === undefined) {
form[key] = [value]
} else if (Array.isArray(form[key])) {
;(form[key] as unknown[]).push(value)
}
} else {
form[key] = value
}
})
value = form
c.req.bodyCache.formData = formData
Expand Down

0 comments on commit 799a8d8

Please sign in to comment.