Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[RFC] 支持类中间件与函数中间件 #37

Open
thonatos opened this issue Jan 31, 2024 · 1 comment
Open

[RFC] 支持类中间件与函数中间件 #37

thonatos opened this issue Jan 31, 2024 · 1 comment

Comments

@thonatos
Copy link
Contributor

thonatos commented Jan 31, 2024

背景

形似 koa 的中间件无法使用 inject 进行注入,使用上与 service 无法对齐;故而新增中间件类型:

  • 类中间件:在类添加 @Middleware({ enable: true }) 注解
  • 函数中间件:在对应的 http method 上添加 @MV({ middlewares: [] }) 注解

需要考虑一下是否在 @artus/pipeline 中添加对类中间件支持?

实现

示例

类中间件

对于全局中间件,参考 nestjs 的语法,支持 Middleware 注解,参数为是否启用,通过 pipeline.run(ctx) 运行

import { ArtusInjectEnum, Inject } from '@artus/core';
import { ArtusxContext, ArtusxNext, Middleware } from '@artusx/core';

@Middleware({
  enable: true,
})
export default class CheckAuthMiddleware {
  @Inject(ArtusInjectEnum.Config)
  config: Record<string, string | number>;

  async use(ctx: ArtusxContext, next: ArtusxNext): Promise<void> {
    const { data } = ctx.context.output;
    data.authed = false;
    console.log('middleware - checkAuth', ctx.context, this.config);
    await next();
  }
}

函数中间件

函数中间件,在 http method 中使用,接收参数为函数中间件数组,通过 koa.use(middlewares) 方式运行

middleware.ts

import { ArtusxContext, ArtusxNext } from '@artusx/core';

export default async function traceTime(_ctx: ArtusxContext, next: ArtusxNext): Promise<void> {
  console.time('trace');
  await next();
  console.timeEnd('trace');
}

controller.ts

import { ArtusInjectEnum, Inject } from '@artus/core';
import { GET, POST, Controller, MW } from '@artusx/core';
import type { ArtusxContext } from '@artusx/core';

import traceTime from '../middleware/traceTime';

@Controller()
export default class HomeController {
  @Inject(ArtusInjectEnum.Config)
  config: Record<string, string | number>;

  @MW([traceTime])
  @GET('/')
  async home(ctx: ArtusxContext) {
    ctx.body = 'home';
  }
}
@thonatos
Copy link
Contributor Author

thonatos commented Feb 6, 2024

执行顺序(类中间件)

配置中增加 config.artusx.middleware 可选参数,对已配置的中间件根据数组顺序排序,并优先于未配置中间件执行。

import traceTime from '../middleware/traceTime';
import checkAuth from '../middleware/checkAuth';

export default {
  artusx: {
    middlewares: [TraceTime, checkAuth],
  }
};
  1. 如需严格控制类中间件的执行顺序,请务必将所有中间件填写在配置中
  2. 如仅需控制部分类中间件,只填写需要控制的中间件即可

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant