src 目录下新增 middleware 目录

新建 xxx.ts

基础模版如下:

  1. import { IMiddleware } from '@midwayjs/core';
  2. import { Middleware } from '@midwayjs/decorator';
  3. import { NextFunction, Context } from '@midwayjs/web';
  4. @Middleware()
  5. export class ErrorCatchMiddleware
  6. implements IMiddleware<Context, NextFunction>
  7. {
  8. resolve() {
  9. return async (ctx: Context, next: NextFunction) => {
  10. // 执行下一个 Web 中间件,最后执行到控制器
  11. // 这里可以拿到下一个中间件或者控制器的返回值
  12. const result = await next();
  13. // 返回给上一个中间件的结果
  14. return result;
  15. };
  16. }
  17. static getName(): string {
  18. return 'ErrorCatch';
  19. }
  20. }

静态 getName 方法,用来指定中间件的名字,方便排查问题。

全局组册

@Configuration({ 
  // ...
})
export class AutoConfiguration {

  @App()
  app: koa.Application;

  async onReady() {
    this.app.useMiddleware(ReportMiddleware);
    // or
    this.app.useMiddleware([ReportMiddleware1, ReportMiddleware2]);
  }
}