-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouters.ts
186 lines (158 loc) · 4.75 KB
/
routers.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
// Copyright 2022-latest the httpland authors. All rights reserved. MIT license.
// This module is browser compatible.
import {
HttpMethodRoutes,
MethodRouterConstructor,
RouterOptions,
URLRouteHandler,
URLRouteHandlerContext,
URLRouterConstructor,
URLRoutes,
} from "./types.ts";
import {
Handler,
HttpMethod,
isOk,
isResponse,
LRUMap,
prop,
safeResponse,
Status,
STATUS_TEXT,
} from "./deps.ts";
import { route2URLPatternRoute, urlPatternRouteFrom } from "./utils.ts";
interface MatchedCache {
readonly handler: URLRouteHandler;
readonly context: URLRouteHandlerContext;
}
type URLCache = { readonly matched: true } & MatchedCache | {
readonly matched: false;
readonly handler: Handler;
};
const MAX_SIZE = 100_0;
/** HTTP request url router.
* {@link URLRouter} provides routing between HTTP request URLs and handlers.
* Request URL are matched with the `URLPatten API`.
*
* ```ts
* import { URLRouter } from "https://deno.land/x/http_router@$VERSION/mod.ts";
* import { serve } from "https://deno.land/std@$VERSION/http/mod.ts";
*
* const handler = URLRouter({
* "/api/students/:name": (request, context) => {
* const greeting = `Hello! ${context.params.name!}`;
* return new Response(greeting);
* },
* "/api/status": () => new Response("OK"),
* });
*
* await serve(handler);
* ```
*/
export const URLRouter: URLRouterConstructor = (routes: URLRoutes, options) => {
const cache = new LRUMap<string, URLCache>(MAX_SIZE);
const iterable = urlPatternRouteFrom(routes);
const entries = Array.from(iterable).map(route2URLPatternRoute).filter(isOk)
.map(prop("value"));
function query(url: string): URLCache {
const cached = cache.has(url);
if (cached) return cache.get(url)!;
for (const [pattern, handler] of entries) {
const result = pattern.exec(url);
if (!result) continue;
const context: URLRouteHandlerContext = {
pattern,
result,
params: result.pathname.groups,
};
const data: URLCache = { handler, context, matched: true };
cache.set(url, data);
return data;
}
const data: URLCache = { handler: handleNotFound, matched: false };
cache.set(url, data);
return data;
}
const handler: Handler = (request) =>
safeResponse(async () => {
const result = query(request.url);
if (!result.matched) return result.handler(request);
return await process(request, (request) =>
result.handler(request, result.context), options);
}, options?.onError);
return handler;
};
async function process(
request: Request,
handle: (request: Request) => Promise<Response> | Response,
options?: RouterOptions,
): Promise<Response> {
const maybeRequest = await options?.beforeEach?.(request.clone()) ??
request;
const response = isResponse(maybeRequest)
? maybeRequest
: await handle(maybeRequest);
return await options?.afterEach?.(response.clone()) ?? response;
}
/** HTTP request method router.
* {@link MethodRouter} provides routing between HTTP request methods and handlers.
*
* ```ts
* import { MethodRouter } from "https://deno.land/x/http_router@$VERSION/mod.ts";
* import { serve } from "https://deno.land/std@$VERSION/http/mod.ts";
*
* const handler = MethodRouter({
* GET: () => new Response("From GET"),
* POST: async (request) => {
* const data = await request.json();
* return new Response("Received data!");
* },
* });
*
* await serve(handler);
* ```
*/
export const MethodRouter: MethodRouterConstructor = (
routes,
{ withHead = true, onError, beforeEach, afterEach } = {},
) => {
if (withHead) {
routes = mapHttpHead(routes);
}
const allow = Object.keys(routes).sort().join(",");
const status = Status.MethodNotAllowed;
const errResponse = new Response(null, {
status: Status.MethodNotAllowed,
statusText: STATUS_TEXT[status],
headers: { allow },
});
const handler: Handler = async (request) => {
const handler = routes[request.method as HttpMethod];
if (!handler) return errResponse;
return await process(request, (request) => handler(request as never), {
beforeEach,
afterEach,
});
};
return (request) => safeResponse(() => handler(request), onError);
};
function mapHttpHead(routes: HttpMethodRoutes): HttpMethodRoutes {
if (!("GET" in routes) || "HEAD" in routes) return routes;
return {
...routes,
HEAD: toEmptyResponseHandler(routes.GET! as Handler),
};
}
function toEmptyResponseHandler(handler: Handler): Handler {
return async (req) => {
const res = await handler(req);
return new Response(null, res);
};
}
function handleNotFound(): Response {
const status = Status.NotFound;
return new Response(null, {
status,
statusText: STATUS_TEXT[status],
});
}