2023-08-18 07:25:48 +00:00
|
|
|
import type { HonoRequest } from '../request.ts'
|
|
|
|
|
2023-09-16 16:09:25 +00:00
|
|
|
export type BodyData = Record<string, string | string[] | File>
|
2022-09-20 13:01:03 +00:00
|
|
|
|
2023-08-05 09:10:12 +00:00
|
|
|
export const parseBody = async <T extends BodyData = BodyData>(
|
2023-09-03 05:43:01 +00:00
|
|
|
request: HonoRequest | Request
|
2023-08-05 09:10:12 +00:00
|
|
|
): Promise<T> => {
|
2023-01-02 23:25:21 +00:00
|
|
|
let body: BodyData = {}
|
2023-09-03 05:43:01 +00:00
|
|
|
const contentType = request.headers.get('Content-Type')
|
|
|
|
|
2022-08-27 02:38:48 +00:00
|
|
|
if (
|
|
|
|
contentType &&
|
|
|
|
(contentType.startsWith('multipart/form-data') ||
|
2023-06-21 13:51:59 +00:00
|
|
|
contentType.startsWith('application/x-www-form-urlencoded'))
|
2022-08-27 02:38:48 +00:00
|
|
|
) {
|
2023-09-03 05:43:01 +00:00
|
|
|
const formData = await request.formData()
|
|
|
|
if (formData) {
|
|
|
|
const form: BodyData = {}
|
|
|
|
formData.forEach((value, key) => {
|
2023-09-16 16:09:25 +00:00
|
|
|
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
|
|
|
|
}
|
2023-09-03 05:43:01 +00:00
|
|
|
})
|
|
|
|
body = form
|
|
|
|
}
|
2022-07-02 06:09:45 +00:00
|
|
|
}
|
2023-08-05 09:10:12 +00:00
|
|
|
return body as T
|
2022-07-02 06:09:45 +00:00
|
|
|
}
|