Web 中间件
Midway Hooks 支持通过函数 + useContext()
来定义 Web 中间件。
语法
中间件仅有 next
一个参数,ctx
需要通过 useContext
获得。你也可以在中间件中使用任意的 Hooks
。
基础示例
以记录请求日志为例:
import { Context } from '@midwayjs/koa';
import { useContext } from '@midwayjs/hooks';
const logger = async (next: any) => {
const ctx = useContext<Context>();
console.log(
`<-- [${ctx.method}] ${ctx.url}`
);
const start = Date.now();
await next();
const cost = Date.now() - start;
console.log(
`--> [${ctx.method}] ${ctx.url} ${cost}ms`
);
};
全局中间件
全局中间件在 configuration.ts
中定义,此处定义的中间件对所有接口生效。
import {
hooks,
createConfiguration,
} from '@midwayjs/hooks';
import logger from './logger';
// Global Middleware
export default createConfiguration({
imports: [
hooks({
middleware: [logger],
}),
],
});