-
Notifications
You must be signed in to change notification settings - Fork 213
/
body.ts
80 lines (66 loc) · 2.79 KB
/
body.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import destr from 'destr'
import type { Encoding, HTTPMethod } from '../types'
import type { H3Event } from '../event'
import { assertMethod } from './request'
const RawBodySymbol = Symbol.for('h3RawBody')
const ParsedBodySymbol = Symbol.for('h3ParsedBody')
const PayloadMethods: HTTPMethod[] = ['PATCH', 'POST', 'PUT', 'DELETE']
/**
* Reads body of the request and returns encoded raw string (default) or `Buffer` if encoding if falsy.
* @param event {H3Event} H3 event or req passed by h3 handler
* @param encoding {Encoding} encoding="utf-8" - The character encoding to use.
*
* @return {String|Buffer} Encoded raw string or raw Buffer of the body
*/
export function readRawBody (event: H3Event, encoding: Encoding = 'utf-8'): Encoding extends false ? Buffer : Promise<string | Buffer | undefined> {
// Ensure using correct HTTP method before attempt to read payload
assertMethod(event, PayloadMethods)
if (RawBodySymbol in event.req) {
const promise = Promise.resolve((event.req as any)[RawBodySymbol])
return encoding ? promise.then(buff => buff.toString(encoding)) : promise
}
// Workaround for unenv issue https://github.com/unjs/unenv/issues/8
if ('body' in event.req) {
return Promise.resolve((event.req as any).body)
}
if (!parseInt(event.req.headers['content-length'] || '')) {
return Promise.resolve(undefined)
}
const promise = (event.req as any)[RawBodySymbol] = new Promise<Buffer>((resolve, reject) => {
const bodyData: any[] = []
event.req
.on('error', (err) => { reject(err) })
.on('data', (chunk) => { bodyData.push(chunk) })
.on('end', () => { resolve(Buffer.concat(bodyData)) })
})
return encoding ? promise.then(buff => buff.toString(encoding)) : promise
}
/** @deprecated Use `h3.readRawBody` */
export const useRawBody = readRawBody
/**
* Reads request body and try to safely parse using [destr](https://github.com/unjs/destr)
* @param event {H3Event} H3 event or req passed by h3 handler
* @param encoding {Encoding} encoding="utf-8" - The character encoding to use.
*
* @return {*} The `Object`, `Array`, `String`, `Number`, `Boolean`, or `null` value corresponding to the request JSON body
*
* ```ts
* const body = await useBody(req)
* ```
*/
export async function readBody<T=any> (event: H3Event): Promise<T> {
if (ParsedBodySymbol in event.req) {
return (event.req as any)[ParsedBodySymbol]
}
// TODO: Handle buffer
const body = await readRawBody(event) as string
if (event.req.headers['content-type'] === 'application/x-www-form-urlencoded') {
const parsedForm = Object.fromEntries(new URLSearchParams(body))
return parsedForm as unknown as T
}
const json = destr(body) as T
(event.req as any)[ParsedBodySymbol] = json
return json
}
/** @deprecated Use `h3.readBody` */
export const useBody = readBody