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
2022-08-05 06:41:28 +09:00

34 lines
1.0 KiB
TypeScript

type JsonPrimitive = boolean | number | string | null
type JsonArray = JsonPrimitive[] | JsonObject[]
type JsonObject = {
[key: string]: JsonPrimitive | JsonObject | JsonArray
}
export type Json = JsonPrimitive | JsonArray | JsonObject
export type Body = string | Json | Record<string, string | File> | ArrayBuffer
export const parseBody = async (r: Request | Response): Promise<Body> => {
const contentType = r.headers.get('Content-Type') || ''
if (contentType.includes('application/json')) {
let body = {}
try {
body = await r.json()
} catch {} // Do nothing
return body
} 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()
}