-
Notifications
You must be signed in to change notification settings - Fork 224
/
body.ts
309 lines (288 loc) · 9.43 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import type { IncomingMessage } from "node:http";
import destr from "destr";
import type { Encoding, HTTPMethod, InferEventInput } from "../types";
import type { H3Event } from "../event";
import { createError } from "../error";
import {
type MultiPartData,
parse as parseMultipartData,
} from "./internal/multipart";
import { assertMethod, getRequestHeader, toWebRequest } from "./request";
import { ValidateFunction, validateData } from "./internal/validate";
import { hasProp } from "./internal/object";
export type { MultiPartData } from "./internal/multipart";
const RawBodySymbol = Symbol.for("h3RawBody");
const ParsedBodySymbol = Symbol.for("h3ParsedBody");
type InternalRequest<T = any> = IncomingMessage & {
[RawBodySymbol]?: Promise<Buffer | undefined>;
[ParsedBodySymbol]?: T;
body?: string | undefined;
};
const PayloadMethods: HTTPMethod[] = ["PATCH", "POST", "PUT", "DELETE"];
/**
* Reads body of the request and returns encoded raw string (default), or `Buffer` if encoding is 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<E extends Encoding = "utf8">(
event: H3Event,
encoding = "utf8" as E,
): E extends false ? Promise<Buffer | undefined> : Promise<string | undefined> {
// Ensure using correct HTTP method before attempt to read payload
assertMethod(event, PayloadMethods);
// Reuse body if already read
const _rawBody =
event._requestBody ||
event.web?.request?.body ||
(event.node.req as any)[RawBodySymbol] ||
(event.node.req as any).rawBody /* firebase */ ||
(event.node.req as any).body; /* unjs/unenv #8 */
if (_rawBody) {
const promise = Promise.resolve(_rawBody).then((_resolved) => {
if (Buffer.isBuffer(_resolved)) {
return _resolved;
}
if (typeof _resolved.pipeTo === "function") {
return new Promise<Buffer>((resolve, reject) => {
const chunks: Buffer[] = [];
_resolved
.pipeTo(
new WritableStream({
write(chunk) {
chunks.push(chunk);
},
close() {
resolve(Buffer.concat(chunks));
},
abort(reason) {
reject(reason);
},
}),
)
.catch(reject);
});
} else if (typeof _resolved.pipe === "function") {
return new Promise<Buffer>((resolve, reject) => {
const chunks: Buffer[] = [];
_resolved
.on("data", (chunk: any) => {
chunks.push(chunk);
})
.on("end", () => {
resolve(Buffer.concat(chunks));
})
.on("error", reject);
});
}
if (_resolved.constructor === Object) {
return Buffer.from(JSON.stringify(_resolved));
}
return Buffer.from(_resolved);
});
return encoding
? promise.then((buff) => buff.toString(encoding))
: (promise as Promise<any>);
}
if (!Number.parseInt(event.node.req.headers["content-length"] || "")) {
return Promise.resolve(undefined);
}
const promise = ((event.node.req as any)[RawBodySymbol] = new Promise<Buffer>(
(resolve, reject) => {
const bodyData: any[] = [];
event.node.req
.on("error", (err) => {
reject(err);
})
.on("data", (chunk) => {
bodyData.push(chunk);
})
.on("end", () => {
resolve(Buffer.concat(bodyData));
});
},
));
const result = encoding
? promise.then((buff) => buff.toString(encoding))
: promise;
return result as E extends false
? Promise<Buffer | undefined>
: Promise<string | undefined>;
}
/**
* Reads request body and tries to safely parse using [destr](https://github.com/unjs/destr).
* @param event H3 event passed by h3 handler
* @param encoding The character encoding to use, defaults to 'utf-8'.
*
* @return {*} The `Object`, `Array`, `String`, `Number`, `Boolean`, or `null` value corresponding to the request JSON body
*
* ```ts
* const body = await readBody(event)
* ```
*/
export async function readBody<
T,
Event extends H3Event = H3Event,
_T = InferEventInput<"body", Event, T>,
>(event: Event, options: { strict?: boolean } = {}): Promise<_T> {
const request = event.node.req as InternalRequest<T>;
if (hasProp(request, ParsedBodySymbol)) {
return request[ParsedBodySymbol] as _T;
}
const contentType = request.headers["content-type"] || "";
const body = await readRawBody(event);
let parsed: T;
if (contentType === "application/json") {
parsed = _parseJSON(body, options.strict ?? true) as T;
} else if (contentType.startsWith("application/x-www-form-urlencoded")) {
// TODO: Extract and pass charset as option (; charset=utf-8)
parsed = _parseURLEncodedBody(body!) as T;
} else if (contentType.startsWith("text/")) {
parsed = body as T;
} else {
parsed = _parseJSON(body, options.strict ?? false) as T;
}
request[ParsedBodySymbol] = parsed;
return parsed as unknown as _T;
}
/**
* Tries to read the request body via `readBody`, then uses the provided validation function and either throws a validation error or returns the result.
* @param event The H3Event passed by the handler.
* @param validate The function to use for body validation. It will be called passing the read request body. If the result is not false, the parsed body will be returned.
* @throws If the validation function returns `false` or throws, a validation error will be thrown.
* @return {*} The `Object`, `Array`, `String`, `Number`, `Boolean`, or `null` value corresponding to the request JSON body.
* @see {readBody}
*
* ```ts
* // With a custom validation function
* const body = await readValidatedBody(event, (body) => {
* return typeof body === "object" && body !== null
* })
*
* // With a zod schema
* import { z } from 'zod'
* const objectSchema = z.object()
* const body = await readValidatedBody(event, objectSchema.safeParse)
* ```
*/
export async function readValidatedBody<
T,
Event extends H3Event = H3Event,
_T = InferEventInput<"body", Event, T>,
>(event: Event, validate: ValidateFunction<_T>): Promise<_T> {
const _body = await readBody(event, { strict: true });
return validateData(_body, validate);
}
/**
* Tries to read and parse the body of a an H3Event as multipart form.
* @param event The H3Event object to read multipart form from.
*
* @return The parsed form data. If no form could be detected because the content type is not multipart/form-data or no boundary could be found.
*
* ```ts
* const formData = await readMultipartFormData(event)
* // The result could look like:
* // [
* // {
* // "data": "other",
* // "name": "baz",
* // },
* // {
* // "data": "something",
* // "name": "some-other-data",
* // },
* // ]
* ```
*/
export async function readMultipartFormData(
event: H3Event,
): Promise<MultiPartData[] | undefined> {
const contentType = getRequestHeader(event, "content-type");
if (!contentType || !contentType.startsWith("multipart/form-data")) {
return;
}
const boundary = contentType.match(/boundary=([^;]*)(;|$)/i)?.[1];
if (!boundary) {
return;
}
const body = await readRawBody(event, false);
if (!body) {
return;
}
return parseMultipartData(body, boundary);
}
/**
* Constructs a FormData object from an event, after converting it to a a web request.
* @param event The H3Event object to read the form data from.
*
* ```ts
* const eventHandler = event => {
* const formData = await readFormData(event)
* const email = formData.get("email")
* const password = formData.get("password")
* }
* ```
*/
export async function readFormData(event: H3Event): Promise<FormData> {
return await toWebRequest(event).formData();
}
/**
* Captures a stream from a request.
* @param event The H3Event object containing the request information.
* @returns Undefined if the request can't transport a payload, otherwise a ReadableStream of the request body.
*/
export function getRequestWebStream(
event: H3Event,
): undefined | ReadableStream {
if (!PayloadMethods.includes(event.method)) {
return;
}
return (
event.web?.request?.body ||
(event._requestBody as ReadableStream) ||
new ReadableStream({
start: (controller) => {
event.node.req.on("data", (chunk) => {
controller.enqueue(chunk);
});
event.node.req.on("end", () => {
controller.close();
});
event.node.req.on("error", (err) => {
controller.error(err);
});
},
})
);
}
// --- Internal ---
function _parseJSON(body = "", strict: boolean) {
if (!body) {
return undefined;
}
try {
return destr(body, { strict });
} catch {
throw createError({
statusCode: 400,
statusMessage: "Bad Request",
message: "Invalid JSON body",
});
}
}
function _parseURLEncodedBody(body: string) {
const form = new URLSearchParams(body);
const parsedForm: Record<string, any> = Object.create(null);
for (const [key, value] of form.entries()) {
if (hasProp(parsedForm, key)) {
if (!Array.isArray(parsedForm[key])) {
parsedForm[key] = [parsedForm[key]];
}
parsedForm[key].push(value);
} else {
parsedForm[key] = value;
}
}
return parsedForm as unknown;
}