-
Notifications
You must be signed in to change notification settings - Fork 179
/
router.ts
198 lines (176 loc) · 4.95 KB
/
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
import {
createRouter as _createRouter,
toRouteMatcher,
RouteMatcher,
} from "radix3";
import { withLeadingSlash } from "ufo";
import type { HTTPMethod, EventHandler } from "./types";
import { createError } from "./error";
import { eventHandler, toEventHandler } from "./event";
export type RouterMethod = Lowercase<HTTPMethod>;
const RouterMethods: RouterMethod[] = [
"connect",
"delete",
"get",
"head",
"options",
"post",
"put",
"trace",
"patch",
];
export type RouterUse = (
path: string,
handler: EventHandler,
method?: RouterMethod | RouterMethod[],
) => Router;
export type AddRouteShortcuts = Record<RouterMethod, RouterUse>;
export interface Router extends AddRouteShortcuts {
add: RouterUse;
use: RouterUse;
handler: EventHandler;
}
export interface RouteNode {
handlers: Partial<Record<RouterMethod | "all", EventHandler>>;
path: string;
}
export interface CreateRouterOptions {
/** @deprecated Please use `preemptive` instead. */
preemtive?: boolean;
preemptive?: boolean;
}
/**
* Create a new h3 router instance.
*/
export function createRouter(opts: CreateRouterOptions = {}): Router {
const _router = _createRouter<RouteNode>({});
const routes: Record<string, RouteNode> = {};
let _matcher: RouteMatcher | undefined;
const router: Router = {} as Router;
// Utilities to add a new route
const addRoute = (
path: string,
handler: EventHandler,
method: RouterMethod | RouterMethod[] | "all",
) => {
let route = routes[path];
if (!route) {
routes[path] = route = { path, handlers: {} };
_router.insert(path, route);
}
if (Array.isArray(method)) {
for (const m of method) {
addRoute(path, handler, m);
}
} else {
route.handlers[method] = toEventHandler(handler, undefined, path);
}
return router;
};
router.use = router.add = (path, handler, method) =>
addRoute(path, handler as EventHandler, method || "all");
for (const method of RouterMethods) {
router[method] = (path, handle) => router.add(path, handle, method);
}
// Handler matcher
const matchHandler = (path = "/", method: RouterMethod = "get") => {
// Remove query parameters for matching
const qIndex = path.indexOf("?");
if (qIndex !== -1) {
path = path.slice(0, Math.max(0, qIndex));
}
// Match route
const matched = _router.lookup(path);
if (!matched || !matched.handlers) {
return {
error: createError({
statusCode: 404,
name: "Not Found",
statusMessage: `Cannot find any route matching ${path || "/"}.`,
}),
};
}
// Match method
let handler: EventHandler | undefined =
matched.handlers[method] || matched.handlers.all;
// Fallback to search for (method) shadowed routes
if (!handler) {
if (!_matcher) {
_matcher = toRouteMatcher(_router);
}
// Default order is less specific to most specific
const _matches = _matcher.matchAll(path).reverse() as RouteNode[];
for (const _match of _matches) {
if (_match.handlers[method]) {
handler = _match.handlers[method];
matched.handlers[method] = matched.handlers[method] || handler;
break;
}
if (_match.handlers.all) {
handler = _match.handlers.all;
matched.handlers.all = matched.handlers.all || handler;
break;
}
}
}
if (!handler) {
return {
error: createError({
statusCode: 405,
name: "Method Not Allowed",
statusMessage: `Method ${method} is not allowed on this route.`,
}),
};
}
return { matched, handler };
};
// Main handle
const isPreemptive = opts.preemptive || opts.preemtive;
router.handler = eventHandler((event) => {
// Match handler
const match = matchHandler(
event.path,
event.method.toLowerCase() as RouterMethod,
);
// No match (method or route)
if ("error" in match) {
if (isPreemptive) {
throw match.error;
} else {
return; // Let app match other handlers
}
}
// Add matched route and params to the context
event.context.matchedRoute = match.matched;
const params = match.matched.params || {};
event.context.params = params;
// Call handler
return Promise.resolve(match.handler(event)).then((res) => {
if (res === undefined && isPreemptive) {
return null; // Send empty content
}
return res;
});
});
// Resolver
router.handler.__resolve__ = async (path) => {
path = withLeadingSlash(path);
const match = matchHandler(path);
if ("error" in match) {
return;
}
let res = {
route: match.matched.path,
handler: match.handler,
};
if (match.handler.__resolve__) {
const _res = await match.handler.__resolve__(path);
if (!_res) {
return;
}
res = { ...res, ..._res };
}
return res;
};
return router;
}