-
Notifications
You must be signed in to change notification settings - Fork 314
Expand file tree
/
Copy pathrequest.ts
More file actions
464 lines (444 loc) · 13.9 KB
/
request.ts
File metadata and controls
464 lines (444 loc) · 13.9 KB
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
import { type ErrorDetails, HTTPError } from "../error.ts";
import { parseQuery } from "./internal/query.ts";
import { validateData } from "./internal/validate.ts";
import { getEventContext } from "./event.ts";
import type { StandardSchemaV1, FailureResult, InferOutput } from "./internal/standard-schema.ts";
import type { ValidateResult, OnValidateError } from "./internal/validate.ts";
import type { H3Event, HTTPEvent } from "../event.ts";
import type { InferEventInput } from "../types/handler.ts";
import type { HTTPMethod } from "../types/h3.ts";
import type { H3EventContext } from "../types/context.ts";
import type { ServerRequest } from "srvx";
const _urlOverrides = new WeakMap<Request, string>();
const _proxyHandler: ProxyHandler<Request> = {
get(target, prop, receiver) {
if (prop === "url") return _urlOverrides.get(receiver);
const value = Reflect.get(target, prop);
return typeof value === "function" ? value.bind(target) : value;
},
};
/**
* Create a lightweight request proxy that overrides only the URL.
*
* Avoids cloning the original request (no `new Request()` allocation).
*/
export function requestWithURL(req: ServerRequest, url: string): ServerRequest {
const proxy = new Proxy(req, _proxyHandler);
_urlOverrides.set(proxy, url);
return proxy;
}
/**
* Create a lightweight request proxy with the base path stripped from the URL pathname.
*/
export function requestWithBaseURL(req: ServerRequest, base: string): ServerRequest {
const url = new URL(req.url);
url.pathname = url.pathname.slice(base.length) || "/";
return requestWithURL(req, url.href);
}
/**
* Convert input into a web [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request).
*
* If input is a relative URL, it will be normalized into a full path based on headers.
*
* If input is already a Request and no options are provided, it will be returned as-is.
*/
export function toRequest(
input: ServerRequest | URL | string,
options?: RequestInit,
): ServerRequest {
if (typeof input === "string") {
let url = input;
if (url[0] === "/") {
const headers = options?.headers ? new Headers(options.headers) : undefined;
const host = headers?.get("host") || "localhost";
const proto = headers?.get("x-forwarded-proto") === "https" ? "https" : "http";
url = `${proto}://${host}${url}`;
}
return new Request(url, options);
} else if (options || input instanceof URL) {
return new Request(input, options);
}
return input;
}
/**
* Get parsed query string object from the request URL.
*
* @example
* app.get("/", (event) => {
* const query = getQuery(event); // { key: "value", key2: ["value1", "value2"] }
* });
*/
export function getQuery<
T,
Event extends H3Event | HTTPEvent = HTTPEvent,
_T = Exclude<InferEventInput<"query", Event, T>, undefined>,
>(event: Event): _T {
const url = (event as H3Event).url || new URL(event.req.url);
return parseQuery(url.search.slice(1)) as _T;
}
export function getValidatedQuery<Event extends HTTPEvent, S extends StandardSchemaV1<any, any>>(
event: Event,
validate: S,
options?: { onError?: (result: FailureResult) => ErrorDetails },
): Promise<InferOutput<S>>;
export function getValidatedQuery<
Event extends HTTPEvent,
OutputT,
InputT = InferEventInput<"query", Event, OutputT>,
>(
event: Event,
validate: (data: InputT) => ValidateResult<OutputT> | Promise<ValidateResult<OutputT>>,
options?: {
onError?: () => ErrorDetails;
},
): Promise<OutputT>;
/**
* Get the query param from the request URL validated with validate function.
*
* You can use a simple function to validate the query object or use a Standard-Schema compatible library like `zod` to define a schema.
*
* @example
* app.get("/", async (event) => {
* const query = await getValidatedQuery(event, (data) => {
* return "key" in data && typeof data.key === "string";
* });
* });
* @example
* import { z } from "zod";
*
* app.get("/", async (event) => {
* const query = await getValidatedQuery(
* event,
* z.object({
* key: z.string(),
* }),
* );
* });
* @example
* import * as v from "valibot";
*
* app.get("/", async (event) => {
* const params = await getValidatedQuery(
* event,
* v.object({
* key: v.string(),
* }),
* {
* onError: ({ issues }) => ({
* statusText: "Custom validation error",
* message: v.summarize(issues),
* }),
* },
* );
* });
*
* @param event The H3Event passed by the handler.
* @param validate The function to use for query validation. It will be called passing the read request query. If the result is not false, the parsed query will be returned.
* @param options Optional options. If provided, the `onError` function will be called with the validation issues if validation fails.
* @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 query.
* @see {getQuery}
*/
export function getValidatedQuery(
event: HTTPEvent,
validate: any,
options?: {
onError?: OnValidateError;
},
): Promise<any> {
const query = getQuery(event);
return validateData(query, validate, options);
}
/**
* Get matched route params.
*
* If `decode` option is `true`, it will decode the matched route params using `decodeURIComponent`.
*
* @example
* app.get("/", (event) => {
* const params = getRouterParams(event); // { key: "value" }
* });
*/
export function getRouterParams(
event: HTTPEvent,
opts: { decode?: boolean } = {},
): NonNullable<H3Event["context"]["params"]> {
// Fallback object needs to be returned in case router is not used (#149)
const context = getEventContext<H3EventContext>(event);
let params = (context.params || {}) as NonNullable<H3Event["context"]["params"]>;
if (opts.decode) {
params = { ...params };
for (const key in params) {
params[key] = decodeURIComponent(params[key]);
}
}
return params;
}
export function getValidatedRouterParams<Event extends HTTPEvent, S extends StandardSchemaV1>(
event: Event,
validate: S,
options?: {
decode?: boolean;
onError?: (result: FailureResult) => ErrorDetails;
},
): Promise<InferOutput<S>>;
export function getValidatedRouterParams<
Event extends HTTPEvent,
OutputT,
InputT = InferEventInput<"routerParams", Event, OutputT>,
>(
event: Event,
validate: (data: InputT) => ValidateResult<OutputT> | Promise<ValidateResult<OutputT>>,
options?: {
decode?: boolean;
onError?: () => ErrorDetails;
},
): Promise<OutputT>;
/**
* Get matched route params and validate with validate function.
*
* If `decode` option is `true`, it will decode the matched route params using `decodeURI`.
*
* You can use a simple function to validate the params object or use a Standard-Schema compatible library like `zod` to define a schema.
*
* @example
* app.get("/:key", async (event) => {
* const params = await getValidatedRouterParams(event, (data) => {
* return "key" in data && typeof data.key === "string";
* });
* });
* @example
* import { z } from "zod";
*
* app.get("/:key", async (event) => {
* const params = await getValidatedRouterParams(
* event,
* z.object({
* key: z.string(),
* }),
* );
* });
* @example
* import * as v from "valibot";
*
* app.get("/:key", async (event) => {
* const params = await getValidatedRouterParams(
* event,
* v.object({
* key: v.pipe(v.string(), v.picklist(["route-1", "route-2", "route-3"])),
* }),
* {
* decode: true,
* onError: ({ issues }) => ({
* statusText: "Custom validation error",
* message: v.summarize(issues),
* }),
* },
* );
* });
*
* @param event The H3Event passed by the handler.
* @param validate The function to use for router params validation. It will be called passing the read request router params. If the result is not false, the parsed router params will be returned.
* @param options Optional options. If provided, the `onError` function will be called with the validation issues if validation fails.
* @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 router params.
* @see {getRouterParams}
*/
export function getValidatedRouterParams(
event: HTTPEvent,
validate: any,
options: {
decode?: boolean;
onError?: OnValidateError;
} = {},
): Promise<any> {
const { decode, ...opts } = options;
const routerParams = getRouterParams(event, { decode });
return validateData(routerParams, validate, opts);
}
/**
* Get a matched route param by name.
*
* If `decode` option is `true`, it will decode the matched route param using `decodeURI`.
*
* @example
* app.get("/", (event) => {
* const param = getRouterParam(event, "key");
* });
*/
export function getRouterParam(
event: HTTPEvent,
name: string,
opts: { decode?: boolean } = {},
): string | undefined {
const params = getRouterParams(event, opts);
return params[name];
}
/**
*
* Checks if the incoming request method is of the expected type.
*
* If `allowHead` is `true`, it will allow `HEAD` requests to pass if the expected method is `GET`.
*
* @example
* app.get("/", (event) => {
* if (isMethod(event, "GET")) {
* // Handle GET request
* } else if (isMethod(event, ["POST", "PUT"])) {
* // Handle POST or PUT request
* }
* });
*/
export function isMethod(
event: HTTPEvent,
expected: HTTPMethod | HTTPMethod[],
allowHead?: boolean,
): boolean {
if (allowHead && event.req.method === "HEAD") {
return true;
}
if (typeof expected === "string") {
if (event.req.method === expected) {
return true;
}
} else if (expected.includes(event.req.method as HTTPMethod)) {
return true;
}
return false;
}
/**
* Asserts that the incoming request method is of the expected type using `isMethod`.
*
* If the method is not allowed, it will throw a 405 error with the message "HTTP method is not allowed".
*
* If `allowHead` is `true`, it will allow `HEAD` requests to pass if the expected method is `GET`.
*
* @example
* app.get("/", (event) => {
* assertMethod(event, "GET");
* // Handle GET request, otherwise throw 405 error
* });
*/
export function assertMethod(
event: HTTPEvent,
expected: HTTPMethod | HTTPMethod[],
allowHead?: boolean,
): void {
if (!isMethod(event, expected, allowHead)) {
throw new HTTPError({ status: 405 });
}
}
/**
* Get the request hostname.
*
* If `xForwardedHost` is `true`, it will use the `x-forwarded-host` header if it exists.
*
* If no host header is found, it will return an empty string.
*
* @example
* app.get("/", (event) => {
* const host = getRequestHost(event); // "example.com"
* });
*/
export function getRequestHost(event: HTTPEvent, opts: { xForwardedHost?: boolean } = {}): string {
if (opts.xForwardedHost) {
const _header = event.req.headers.get("x-forwarded-host");
const xForwardedHost = (_header || "").split(",").shift()?.trim();
if (xForwardedHost) {
return xForwardedHost;
}
}
return event.req.headers.get("host") || "";
}
/**
* Get the request protocol.
*
* If `x-forwarded-proto` header is set to "https", it will return "https". You can disable this behavior by setting `xForwardedProto` to `false`.
*
* If protocol cannot be determined, it will default to "http".
*
* @example
* app.get("/", (event) => {
* const protocol = getRequestProtocol(event); // "https"
* });
*/
export function getRequestProtocol(
event: HTTPEvent | H3Event,
opts: { xForwardedProto?: boolean } = {},
): "http" | "https" | (string & {}) {
if (opts.xForwardedProto !== false) {
const forwardedProto = event.req.headers.get("x-forwarded-proto");
if (forwardedProto === "https") {
return "https";
}
if (forwardedProto === "http") {
return "http";
}
}
const url = (event as H3Event).url || new URL(event.req.url);
return url.protocol.slice(0, -1);
}
/**
* Generated the full incoming request URL.
*
* If `xForwardedHost` is `true`, it will use the `x-forwarded-host` header if it exists.
*
* If `xForwardedProto` is `false`, it will not use the `x-forwarded-proto` header.
*
* @example
* app.get("/", (event) => {
* const url = getRequestURL(event); // "https://example.com/path"
* });
*/
export function getRequestURL(
event: HTTPEvent | H3Event,
opts: { xForwardedHost?: boolean; xForwardedProto?: boolean } = {},
): URL {
const url = new URL((event as H3Event).url || event.req.url);
url.protocol = getRequestProtocol(event, opts);
if (opts.xForwardedHost) {
const host = getRequestHost(event, opts);
if (host) {
url.host = host;
if (!/:\d+$/.test(host)) {
url.port = "";
}
}
}
return url;
}
/**
* Try to get the client IP address from the incoming request.
*
* If `xForwardedFor` is `true`, it will use the `x-forwarded-for` header if it exists.
*
* If IP cannot be determined, it will default to `undefined`.
*
* @example
* app.get("/", (event) => {
* const ip = getRequestIP(event); // "192.0.2.0"
* });
*/
export function getRequestIP(
event: HTTPEvent,
opts: {
/**
* Use the X-Forwarded-For HTTP header set by proxies.
*
* Note: Make sure that this header can be trusted (your application running behind a CDN or reverse proxy) before enabling.
*/
xForwardedFor?: boolean;
} = {},
): string | undefined {
if (opts.xForwardedFor) {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For#syntax
const _header = event.req.headers.get("x-forwarded-for");
if (_header) {
const xForwardedFor = _header.split(",")[0].trim();
if (xForwardedFor) {
return xForwardedFor;
}
}
}
return (event.req.context?.clientAddress as string) || event.req.ip || undefined;
}