2022-09-20 13:01:03 +00:00
|
|
|
export type BodyData = Record<string, string | number | boolean | File>
|
|
|
|
|
|
|
|
export async function parseBody<BodyType extends BodyData>(
|
|
|
|
r: Request | Response
|
|
|
|
): Promise<BodyType> {
|
2022-08-27 02:38:48 +00:00
|
|
|
let body: Record<string, string | File> = {}
|
|
|
|
const contentType = r.headers.get('Content-Type')
|
|
|
|
if (
|
|
|
|
contentType &&
|
|
|
|
(contentType.startsWith('multipart/form-data') ||
|
|
|
|
contentType === 'application/x-www-form-urlencoded')
|
|
|
|
) {
|
2022-07-02 06:09:45 +00:00
|
|
|
const form: Record<string, string | File> = {}
|
2022-08-27 02:38:48 +00:00
|
|
|
body = [...(await r.formData())].reduce((acc, cur) => {
|
2022-07-02 06:09:45 +00:00
|
|
|
acc[cur[0]] = cur[1]
|
|
|
|
return acc
|
|
|
|
}, form)
|
|
|
|
}
|
2022-09-20 13:01:03 +00:00
|
|
|
return body as BodyType
|
2022-07-02 06:09:45 +00:00
|
|
|
}
|