47 lines
1.6 KiB
JavaScript
47 lines
1.6 KiB
JavaScript
'use strict';
|
|||
|
|
// 极简路由匹配:按声明顺序比对 method + path,返回第一条命中的路由及其参数(原样字符串,不解码)。
|
||
|
|
// path 写法:静态段原样匹配;:name 匹配一段(不含 /);:name(约束) 用下表的命名约束或直接写正则;
|
||
|
|
// 末尾 *name 匹配剩余全部(可为空、可含 /)。
|
||
|
|
const CONSTRAINTS = {
|
||
|
|
uuid: '[a-f0-9-]{36}',
|
||
|
|
hexid: '[a-f0-9-]+',
|
||
|
|
day: '\\d{4}-\\d{2}-\\d{2}',
|
||
|
|
member: '[A-Za-z0-9_-]+',
|
||
|
|
word: '[a-z]+',
|
||
|
|
};
|
||
|
|
const escape = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||
|
|
function compile(path) {
|
||
|
|
const names = [];
|
||
|
|
const source = path
|
||
|
|
.split('/')
|
||
|
|
.map(part => {
|
||
|
|
const param = part.match(/^:(\w+)(?:\((.+)\))?$/);
|
||
|
|
if (param) {
|
||
|
|
names.push(param[1]);
|
||
|
|
return '(' + (param[2] ? (CONSTRAINTS[param[2]] ?? param[2]) : '[^/]+') + ')';
|
||
|
|
}
|
||
|
|
const rest = part.match(/^\*(\w+)$/);
|
||
|
|
if (rest) {
|
||
|
|
names.push(rest[1]);
|
||
|
|
return '(.*)';
|
||
|
|
}
|
||
|
|
return escape(part);
|
||
|
|
})
|
||
|
|
.join('/');
|
||
|
|
return { regex: new RegExp('^' + source + '$'), names };
|
||
|
|
}
|
||
|
|
function createRouter(routes) {
|
||
|
|
const compiled = routes.map(route => ({ route, ...compile(route.path) }));
|
||
|
|
return {
|
||
|
|
match(method, pathname, accept = () => true) {
|
||
|
|
for (const { route, regex, names } of compiled) {
|
||
|
|
if (route.method !== method) continue;
|
||
|
|
const found = pathname.match(regex);
|
||
|
|
if (!found || !accept(route)) continue;
|
||
|
|
return { route, params: Object.fromEntries(names.map((name, i) => [name, found[i + 1]])) };
|
||
|
|
}
|
||
|
|
return null;
|
||
|
|
},
|
||
|
|
};
|
||
|
|
}
|
||
|
|
module.exports = { createRouter, compile, CONSTRAINTS };
|