Skip to content
Myr

fix(validator): `form` supports multiple values with `foo[]` (#2639)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* fix(validator): `form` supports multiple values `foo[]` * denoify

authored by Yusuke Wada · committed by GitHub · parent 413c936 · Browse files · 3 files+45 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+45 added−2 removed

  • tests:+27 added−0 removed
  • other:+18 added−2 removed

3 files+45 added−2 removed

modified:deno_dist/validator/validator.ts+9 added-1 removed
modified:src/validator/validator.test.ts+27 added
255 unmodified lines
256 }257 })258})259260describe('Form with multiple values', () => {261 const app = new Hono()262263 app.post(264 '/',265 validator('form', (value) => value),266 async (c) => {267 const data = c.req.valid('form')268 return c.json(data)269 }270 )271272 it('Should return `foo[]` as an array', async () => {273 const form = new FormData()274 form.append('foo[]', 'bar1')275 form.append('foo[]', 'bar2')276 const res = await app.request('/', {277 method: 'POST',278 body: form,279 })280 expect(res.status).toBe(200)281 expect(await res.json()).toEqual({282 'foo[]': ['bar1', 'bar2'],283 })284 })285})286287describe('Validator middleware with a custom validation function', () => {288 const app = new Hono()289290 const validationFunction: ValidationFunction<{ id: string }, { id: number }> = (v) => {
725 unmodified lines
modified:src/validator/validator.ts+9 added-1 removed
91 unmodified lines
92 const arrayBuffer = await c.req.arrayBuffer()93 const formData = await bufferToFormData(arrayBuffer, contentType)94 const form: BodyData = {}95 formData.forEach((value, key) => {96 if (key.endsWith('[]')) {97 if (form[key] === undefined) {98 form[key] = [value]99 } else if (Array.isArray(form[key])) {100 ;(form[key] as unknown[]).push(value)101 }102 } else {96 form[key] = value103 form[key] = value104 }105 })106 value = form107 c.req.bodyCache.formData = formData108 } catch (e) {
35 unmodified lines