实现说明
活动部件是函数 toContext。
异步部分依次 await 结果,顺序可预测。
结果是全新构造,调用方可以放心保留自己的原件。
使用要点
node:http是 Node.js 内建模块——随运行时自带,无需安装。- 每一步打印都带着自己的标签:
context:、handling。
常见问题
toContext 会修改传入的参数吗?
没有原地修改——函数读取输入并返回新值。
它从项目之外导入了什么?
只有 node:http,而它是 Node.js 内建的——随运行时提供。
主要签名是 function toContext(req: IncomingMessage)
核心语句
return { method: req.method ?? 'GET', path: req.url ?? '/' };
type RouteHandler = (ctx: RouteContext) => Promise<void>;
return Promise.resolve();
代码示例
// import type:只引用类型,转译后整行被擦除
import type { IncomingMessage } from 'node:http';
interface RouteContext {
method: string;
path: string;
}
function toContext(req: IncomingMessage): RouteContext {
return { method: req.method ?? 'GET', path: req.url ?? '/' };
}
const fake = { method: 'POST', url: '/orders' } as unknown as IncomingMessage;
console.log('context:', toContext(fake).method, toContext(fake).path);
type RouteHandler = (ctx: RouteContext) => Promise<void>;
const handler: RouteHandler = (ctx) => {
console.log('handling', ctx.method, ctx.path);
return Promise.resolve();
};
handler(toContext(fake));