deno.land / x / servest@v1.3.4 / router.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
// Copyright 2019-2020 Yusuke Sakurai. All rights reserved. MIT license.import { findLongestAndNearestMatches } from "./_matcher.ts";import { ServeHandler, ServerRequest } from "./server.ts";import { RoutingError } from "./error.ts";import { acceptable, acceptWebSocket, WebSocket,} from "./vendor/https/deno.land/std/ws/mod.ts";import { assert } from "./vendor/https/deno.land/std/testing/asserts.ts";
/** Router handler */export interface RouteHandler { (req: ServerRequest): | void | Promise<void>;}
/** WebSocket Handler */export interface WebSocketHandler { ( sock: WebSocket, req: ServerRequest, ): void | Promise<void>;}
/** Global error handler for requests */export interface ErrorHandler { ( e: any | RoutingError, req: ServerRequest, ): void | Promise<void>;}
export interface Route { // internal handleRoute(prefix: string, req: ServerRequest): Promise<void>;}
function isRoute(x: any): x is Route { return typeof x?.handleRoute === "function";}
export interface Router extends Route { /** * Set global middleware. * It will be called for each request on any routes. * */ use(...handlers: ServeHandler[]): void;
/** * Register route with given pattern. * It will be called for every http method, * Examples: * router.handle("/", ...) => Called if request path exactly matches "/". * router.handle(/^\//, ...) => Called if request path matches given regexp. * */ handle(pattern: string | RegExp, ...handlers: RouteHandler[]): void;
/** * Register route with given prefixer. * This is similar to router.handle() but different in several points: * - Only string prefix can be passed. * - Handlers will be called if req.path STARTS WITH prefix * - route() doesn't designate a single route handler set before dispatching. * This means it will keep calling all handler sets that matches prefixer until someone responds. * - route can accept Router * Examples * router.route("/users", ...) => Called if request path STARTS WITH "/users". */ route(prefix: string, ...handlers: (RouteHandler | Router)[]): void;
/** * Register GET/HEAD route. This is shortcut for handle(); * */ get(pattern: string | RegExp, ...handlers: RouteHandler[]): void;
/** Register POST route. This is shortcut for handle() */ post(pattern: string | RegExp, ...handlers: RouteHandler[]): void;
/** Register PUT route */ put(pattern: string | RegExp, ...handlers: RouteHandler[]): void;
/** Register DELETE route */ delete(pattern: string | RegExp, ...handlers: RouteHandler[]): void;
/** Register OPTIONS route */ options(pattern: string | RegExp, ...handlers: RouteHandler[]): void;
/** Accept ws upgrade */ ws(pattern: string | RegExp, handler: WebSocketHandler): void; ws( pattern: string | RegExp, handlers: RouteHandler[], handler: WebSocketHandler, ): void;
/** * Set global error handler. * All unhandled promise rejections occured on processing requests will be passed . * Only one handler can be set for one router. */ catch(handler: ErrorHandler): void;
/** * Set global finalizer. * Every request will reach this handler. * Note that request may already has been responded by other handlers. * Only one handler can be set for one router. */ finally(handler: ServeHandler): void;}
export function createRouter(): Router { const middlewareList: ServeHandler[] = []; const routes: { pattern: string | RegExp; methods?: string[]; handlers: RouteHandler[]; wsHandler?: WebSocketHandler; }[] = []; const prefixers: { prefix: string; handlers: RouteHandler[]; }[] = [];
let errorHandler: ErrorHandler | undefined; let finalHandler: ServeHandler | undefined;
function handle(pattern: string | RegExp, ...handlers: RouteHandler[]) { routes.push({ pattern, handlers }); }
function route(prefix: string, ...handlers: RouteHandler[]) { prefixers.push({ prefix, handlers }); }
function get(pattern: string | RegExp, ...handlers: RouteHandler[]) { routes.push({ pattern, methods: ["GET", "HEAD"], handlers, }); }
function post(pattern: string | RegExp, ...handlers: RouteHandler[]) { routes.push({ pattern, methods: ["POST"], handlers }); }
function put(pattern: string | RegExp, ...handlers: RouteHandler[]) { routes.push({ pattern, methods: ["PUT"], handlers }); }
function _delete(pattern: string | RegExp, ...handlers: RouteHandler[]) { routes.push({ pattern, methods: ["DELETE"], handlers }); }
function options(pattern: string | RegExp, ...handlers: RouteHandler[]) { routes.push({ pattern, methods: ["OPTIONS"], handlers }); }
function use(...handlers: ServeHandler[]) { middlewareList.push(...handlers); }
function ws(pattern: string | RegExp, ...args: any[]) { if (Array.isArray(args[0])) { routes.push({ pattern, handlers: args[0], wsHandler: args[1] }); } else if (typeof args[0] === "function") { routes.push({ pattern, handlers: [], wsHandler: args[0] }); } else { throw new Error("invalid function arguments"); } }
function _catch(handler: ErrorHandler) { errorHandler = handler; }
function _finally(handler: ServeHandler) { finalHandler = handler; }
async function chainRoutes( prefix: string, req: ServerRequest, handlers: (RouteHandler | Router)[], ): Promise<boolean> { for (const handler of handlers) { if (isRoute(handler)) { await handler.handleRoute(prefix, req); } else { await handler(req); } if (req.isResponded()) { return true; } } return false; } async function handleRouteInternal( parentMatch: string, req: ServerRequest, ): Promise<void> { for (const handler of middlewareList) { await handler(req); if (req.isResponded()) { return; } } const subpath = req.path.slice(parentMatch.length) || "/"; for (const { prefix, handlers } of prefixers) { if (subpath.startsWith(prefix)) { const match = subpath.match(new RegExp(`^${prefix}`)); assert(match != null); req.match = match; if (await chainRoutes(parentMatch + prefix, req, handlers)) { return; } } } const matches = findLongestAndNearestMatches( subpath, routes.map((v) => v.pattern), ); if (matches.length > 0) { for (const [i, match] of matches) { const { methods, handlers, wsHandler } = routes[i]; if (methods && !methods.includes(req.method)) { continue; } req.match = match; if (await chainRoutes(parentMatch + match, req, handlers)) { return; } if (wsHandler && acceptable(req)) { const sock = await acceptWebSocket(req); req.markAsResponded(101); wsHandler(sock, req); } } if (!req.isResponded()) { throw new RoutingError(404); } } else { throw new RoutingError(404); } } const handleRoute = async (parentMatch: string, req: ServerRequest) => { try { await handleRouteInternal(parentMatch, req); } catch (e) { if (errorHandler) { await errorHandler(e, req); if (!req.isResponded()) { throw e; } } else { throw e; } } finally { finalHandler?.(req); } }; return { handleRoute, use, handle, route, get, post, options, put, delete: _delete, ws, catch: _catch, finally: _finally, };}
servest

Version Info

Tagged at
2 years ago