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

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

+51
View File
@@ -0,0 +1,51 @@
'use strict';
// 路由表分发。路由字段:
// method, path 匹配条件(见 router.js)
// auth 'public'(登录前处理)| 'user'(默认;/api/ 与 /print/ 先 401/409 校验)
// when(app) 可选;返回 false 时视同未声明(如演示登录只在演示模式存在)
// role: 'owner' 店主专用;默认在读请求体之前校验,ownerCheck: 'transact' 改为在事务内校验
// direct: true POST 由处理函数自行读请求体(旧代码中在通用写入流程之前处理的 POST)
// write: true POST 在 transact(操作号幂等)内执行;syncTeamFunds 默认 true
// project(ctx, result) 写入结果(含幂等重放的缓存结果)发出前的投影
// contentType 非 JSON 响应类型(如打印 HTML)
// raw: true 处理函数自行写出响应(下载)
// handler(ctx) ctx = {req, res, url, params, query, body, actor, ledger, rawLedger, app}
// 未匹配的 /api/、/print/ 请求:GET 直接 404;POST 照常读请求体、复核会话、进入 transact 后再 404,
// 因此请求体过大/非 JSON、会话失效、操作号无效等错误仍先于 404 返回。
const { fail, owner } = require('../ledger');
const { send, notFound } = require('./http');
const { readBody } = require('./middleware/body');
const UNMATCHED = {
GET: { method: 'GET', handler: notFound },
POST: { method: 'POST', write: true, handler: notFound },
};
async function runRoute(route, ctx) {
const { req, res, actor, app } = ctx;
if (route.role === 'owner' && route.ownerCheck !== 'transact') owner(actor);
if (route.method === 'GET' || route.direct) {
const data = await route.handler(ctx);
if (!route.raw) send(res, 200, data, route.contentType);
return;
}
ctx.body = await readBody(req);
const key = req.headers['idempotency-key'];
// 读取请求体期间账号可能已被停用或重置密码,写入前再次核验会话。
const checkedActor = app.user(req);
if (!checkedActor || checkedActor.id !== actor.id) fail('登录已失效,请重新登录', 401);
if (!route.write) return send(res, 200, route.handler(ctx));
const result = ctx.ledger.transact(
key,
actor,
{ route: ctx.url.pathname, body: ctx.body },
() => {
if (route.role === 'owner' && route.ownerCheck === 'transact') owner(actor);
return route.handler(ctx);
},
{ syncTeamFunds: route.syncTeamFunds !== false },
);
send(res, 200, route.project ? route.project(ctx, result) : result);
}
module.exports = { runRoute, UNMATCHED };