路由表化:新增路由匹配器、中间件与表驱动分发,迁移店铺设置/员工/货盘路由

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
黄健铭andClaude Opus 5.5 committed 2026-12-04 12:26:22 -08:00
1 parent 2b9cb825be
commit e082069f55
14 files changed
+525 -197

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
'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 };