-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathhandler.ts
73 lines (69 loc) · 2.18 KB
/
handler.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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import type { IncomingMessage, ServerResponse } from 'node:http';
/**
* Represents a middleware function for handling HTTP requests in a Node.js environment.
*
* @param req - The incoming HTTP request object.
* @param res - The outgoing HTTP response object.
* @param next - A callback function that signals the completion of the middleware or forwards the error if provided.
*
* @returns A Promise that resolves to void or simply void. The handler can be asynchronous.
*/
export type NodeRequestHandlerFunction = (
req: IncomingMessage,
res: ServerResponse,
next: (err?: unknown) => void,
) => Promise<void> | void;
/**
* Attaches metadata to the handler function to mark it as a special handler for Node.js environments.
*
* @typeParam T - The type of the handler function.
* @param handler - The handler function to be defined and annotated.
* @returns The same handler function passed as an argument, with metadata attached.
*
* @example
* Usage in an Express application:
* ```ts
* const app = express();
* export default createNodeRequestHandler(app);
* ```
*
* @example
* Usage in a Hono application:
* ```ts
* const app = new Hono();
* export default createNodeRequestHandler(async (req, res, next) => {
* try {
* const webRes = await app.fetch(createWebRequestFromNodeRequest(req));
* if (webRes) {
* await writeResponseToNodeResponse(webRes, res);
* } else {
* next();
* }
* } catch (error) {
* next(error);
* }
* }));
* ```
*
* @example
* Usage in a Fastify application:
* ```ts
* const app = Fastify();
* export default createNodeRequestHandler(async (req, res) => {
* await app.ready();
* app.server.emit('request', req, res);
* res.send('Hello from Fastify with Node Next Handler!');
* }));
* ```
*/
export function createNodeRequestHandler<T extends NodeRequestHandlerFunction>(handler: T): T {
(handler as T & { __ng_node_request_handler__?: boolean })['__ng_node_request_handler__'] = true;
return handler;
}