@Header@Query@Body 等等之所以能将请求的属性注入到控制器的方法参数上,全靠方法参数解释器。

定义

  1. export interface MethodArgsResolver {
  2. readonly priority: number;
  3. resolve(metadata: any, args: any[]): Promise<void>;
  4. }

实现

  1. @Component(MethodArgsResolver)
  2. export class QueryMethodArgsResolver implements MethodArgsResolver {
  3. readonly priority = 400;
  4. async resolve(metadata: any, args: any[]): Promise<void> {
  5. const query: any = Context.getCurrent().request.query;
  6. const queryMetadatas = <QueryMetadata[]>metadata.queryMetadata;
  7. if (queryMetadatas && query !== undefined) {
  8. for (const m of queryMetadatas) {
  9. args[m.parameterIndex] = m.name ? query[m.name] : query;
  10. }
  11. }
  12. }
  13. }