router.ts
2.05 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
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { Route, ServerCtx } from './context';
interface CompiledRoute {
method: string;
regex: RegExp;
keys: string[];
handle: Route['handle'];
}
/** 把 `:param` / `*` 路径模式编译成正则 + 参数名列表。 */
function compile(path: string): { regex: RegExp; keys: string[] } {
const keys: string[] = [];
const parts = path.split('/').map((seg) => {
if (seg === '*') {
keys.push('splat'); // 通配段
return '(.*?)';
}
const named = /^:(.+)$/.exec(seg);
if (named) {
keys.push(named[1]);
return '([^/]+)';
}
// 转义正则元字符(保留我们自己的 token 已先行处理)
return seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
});
const regex = new RegExp('^' + parts.join('/') + '/?$');
return { regex, keys };
}
/**
* 极薄路由表:按注册顺序匹配 method + path,命中后调用 handler。
* 无框架、无中间件链;handler 直接操作 req/res,保持原生语义。
*/
export function createRouter(routes: Route[]) {
const compiled: CompiledRoute[] = routes.map((r) => {
const { regex, keys } = compile(r.path);
return { method: r.method, regex, keys, handle: r.handle };
});
return {
async dispatch(
ctx: ServerCtx,
req: IncomingMessage,
res: ServerResponse,
url: URL,
): Promise<boolean> {
for (const c of compiled) {
if (c.method !== req.method) continue;
const m = c.regex.exec(url.pathname);
if (!m) continue;
const params: Record<string, string> = {};
c.keys.forEach((k, i) => {
params[k] = decodeURIComponent(m[i + 1]);
});
const handled = await c.handle({ ctx, req, res, url, params });
if (handled !== false) return true;
}
return false;
},
};
}