0
0
mirror of https://github.com/honojs/hono.git synced 2024-11-21 18:18:57 +01:00

fix(validator): don't return a FormData if formData is cached (#3067)

* fix(validator): don't return a FormData if formData is cached

* fixed typo

* test the value
This commit is contained in:
Yusuke Wada 2024-07-01 16:29:34 +09:00 committed by GitHub
parent 94f47ec2e6
commit 2d452f2bd2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 55 additions and 23 deletions

View File

@ -910,6 +910,24 @@ describe('Clone Request object', () => {
}
)
app.post(
'/cached',
async (c, next) => {
await c.req.parseBody()
await next()
},
validator('form', (value) => {
if (value instanceof FormData) {
throw new Error('The value should not be a FormData')
}
return value
}),
(c) => {
const v = c.req.valid('form')
return c.json(v)
}
)
it('Should not throw the error with c.req.parseBody()', async () => {
const body = new FormData()
body.append('foo', 'bar')
@ -920,6 +938,18 @@ describe('Clone Request object', () => {
const res = await app.request(req)
expect(res.status).toBe(200)
})
it('Should not be an instance of FormData if the formData is cached', async () => {
const body = new FormData()
body.append('foo', 'bar')
const req = new Request('http://localhost/cached', {
method: 'POST',
body: body,
})
const res = await app.request(req)
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ foo: 'bar' })
})
})
})

View File

@ -83,33 +83,35 @@ export const validator = <
break
}
let formData: FormData
if (c.req.bodyCache.formData) {
value = await c.req.bodyCache.formData
break
formData = await c.req.bodyCache.formData
} else {
try {
const arrayBuffer = await c.req.arrayBuffer()
formData = await bufferToFormData(arrayBuffer, contentType)
c.req.bodyCache.formData = formData
} catch (e) {
let message = 'Malformed FormData request.'
message += e instanceof Error ? ` ${e.message}` : ` ${String(e)}`
throw new HTTPException(400, { message })
}
}
try {
const arrayBuffer = await c.req.arrayBuffer()
const formData = await bufferToFormData(arrayBuffer, contentType)
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)
}
} else {
form[key] = value
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)
}
})
value = form
c.req.bodyCache.formData = formData
} catch (e) {
let message = 'Malformed FormData request.'
message += e instanceof Error ? ` ${e.message}` : ` ${String(e)}`
throw new HTTPException(400, { message })
}
} else {
form[key] = value
}
})
value = form
break
}
case 'query':