2022-08-04 23:10:41 +00:00
|
|
|
export type Body = string | object | Record<string, string | File>
|
2022-08-03 02:24:51 +00:00
|
|
|
|
|
|
|
export const parseBody = async (r: Request | Response): Promise<Body> => {
|
2022-07-02 06:09:45 +00:00
|
|
|
const contentType = r.headers.get('Content-Type') || ''
|
|
|
|
|
|
|
|
if (contentType.includes('application/json')) {
|
2022-07-31 13:19:28 +00:00
|
|
|
let body = {}
|
|
|
|
try {
|
|
|
|
body = await r.json()
|
|
|
|
} catch {} // Do nothing
|
|
|
|
return body
|
2022-07-02 06:09:45 +00:00
|
|
|
} else if (contentType.includes('application/text')) {
|
|
|
|
return await r.text()
|
|
|
|
} else if (contentType.startsWith('text')) {
|
|
|
|
return await r.text()
|
|
|
|
} else if (contentType.includes('form')) {
|
|
|
|
const form: Record<string, string | File> = {}
|
|
|
|
const data = [...(await r.formData())].reduce((acc, cur) => {
|
|
|
|
acc[cur[0]] = cur[1]
|
|
|
|
return acc
|
|
|
|
}, form)
|
|
|
|
return data
|
|
|
|
}
|
|
|
|
|
|
|
|
return r.arrayBuffer()
|
|
|
|
}
|