0
0
mirror of https://github.com/honojs/hono.git synced 2024-12-01 10:51:01 +00:00
hono/deno_dist/utils/body.ts
Bakunya | Kirisaki Rem f25ae8aa5c
feat: Improvement of Parse Body (#1461)
* feat: improvement of parse body

* feat: add test for improvement of parse body commit

* chore: denoify and fix:format

* rm: test file on deno_dist

---------

Co-authored-by: irvan hakim <irvanhakim.dev@gmail.com>
2023-09-17 01:09:25 +09:00

37 lines
981 B
TypeScript

import type { HonoRequest } from '../request.ts'
export type BodyData = Record<string, string | string[] | File>
export const parseBody = async <T extends BodyData = BodyData>(
request: HonoRequest | Request
): Promise<T> => {
let body: BodyData = {}
const contentType = request.headers.get('Content-Type')
if (
contentType &&
(contentType.startsWith('multipart/form-data') ||
contentType.startsWith('application/x-www-form-urlencoded'))
) {
const formData = await request.formData()
if (formData) {
const form: BodyData = {}
formData.forEach((value, key) => {
if (key.slice(-2) === '[]') {
if (!form[key]) {
form[key] = [value.toString()]
} else {
if (Array.isArray(form[key])) {
;(form[key] as string[]).push(value.toString())
}
}
} else {
form[key] = value
}
})
body = form
}
}
return body as T
}