Malagu 中间件与 Koa 里面的中间件是一样的概念,实现了一个洋葱模型,通过中间件可以对请求的处理进行扩展增强,Malagu 框架本身很多功能就是通过中间件来实现的,比如 Cookies、Session、认证和授权等等。
Middleware
export interface Middleware {handle(ctx: Context, next: () => Promise<void>): Promise<void>;readonly priority: number;}
实现自定义中间件
@Component(Middleware)export class CookiesMiddleware implements Middleware {@Autowired(CookiesFactory)protected readonly cookiesFactory: CookiesFactory;async handle(ctx: Context, next: () => Promise<void>): Promise<void> {if (ctx.request) {Context.setCookies(await this.cookiesFactory.create());}await next();}readonly priority = COOKIES_MIDDLEWARE_PRIORITY;}
只需要实现 Middleware,并且加上装饰器 @Component(Middleware) 就实现并注册了自己的中间件了。
注意:调用 next 方法的时候一定要记得加 await,否则会导致全局异常处理失效的问题。
