Skip to content

Application 与装饰器

src/core/Application 是框架的 HTTP 层:封装 Express、扫描业务模块、注册路由,并编排鉴权、校验、限流、防重、序列化、异常与日志。

请求处理顺序(非 raw)

  1. 鉴权
  2. 限流 / 防重复提交
  3. 参数注入
  4. @Validate() 校验(若开启)
  5. Controller 业务
  6. ObjectMapper.writeValue 序列化
  7. ResponseData.success 返回
  8. 异常 → handleException(Advice)
  9. finally 异步写操作日志(若配置)

Controller 与 HTTP 方法

ts
@Controller('/api/user')
export default class UserController {
  @GetController('/list')
  async list() { /* ... */ }

  @PostController('/create')
  @Validate()
  async create(@RequestBody() body: CreateUserDTO) { /* ... */ }
}
装饰器作用
@Controller(prefix?)类装饰器,统一路径前缀
@GetController / Post / Put / DeleteHTTP 方法

静态路径写在动态路径之前。

参数注入

装饰器注入内容
@RequestBody()req.body
@RequestQuery()req.query
@RequestPath() / @RequestPath(n)路径参数
@RequestHeader() / @RequestCookie()头 / Cookie

常用方法装饰器

装饰器说明
@AuthCheckLogin / Role / Permission / @AuthIgnore鉴权,见 Auth
@Validate()入参校验,见 Validate
@Log({ title, business })异步操作日志,见 Log
@RateLimiter / @RepeatSubmit限流 / 防重,见 限流

函数式注册

ts
Application.POST(path, handler, {
  auth: { permissions: ['x'] },
  validate: true, // 一般装饰器更方便
  log: { title: '...' },
  raw: false,
})

raw: true:不包装 ResponseData,也不走 ObjectMapper(下载 / 上传)。

统一响应

ts
{ code: number, message: string, data: T | null }

异常统一走 Exception;成功数据经 Json 序列化。

相关

基于 VitePress 构建