如何在typescript中从类装饰器向方法装饰器注入值?

如何在typescript中从类装饰器向方法装饰器注入值?,typescript,Typescript,我已经开始在TypeScript中使用decorator,它可以工作,我创建了Get、Post、Put和Delete decorator,可以添加到控制器方法中,并将path作为参数,它可以工作。但我希望能够使用类装饰器设置默认路径。现在,当我在任何方法装饰器中使用console.log\u target时,都会得到一个空对象。预期行为:我希望_目标变量具有path参数,由控制器类装饰器设置。我的代码是: @Controller("/api/auth") // class d

我已经开始在TypeScript中使用decorator,它可以工作,我创建了Get、Post、Put和Delete decorator,可以添加到控制器方法中,并将
path
作为参数,它可以工作。但我希望能够使用类装饰器设置默认路径。现在,当我在任何方法装饰器中使用console.log
\u target
时,都会得到一个空对象。预期行为:我希望_目标变量具有path参数,由控制器类装饰器设置。我的代码是:

@Controller("/api/auth") // class decorator
export function Controller(path: string): ClassDecorator {
  return function (constructor: Function) {
    constructor.prototype.path = path;
  };
}
@Get(“/api/auth/init”)//方法修饰符
导出函数Get(路径:string):MethodDecorator{
返回函数(
_目标:任何,
_propertyKey:字符串|符号,
描述符:PropertyDescriptor
):无效{
常量响应=异步(请求:请求,响应:承诺=>{
试一试{
返回等待描述符值(req,res);
}捕获(e){
返回res.status(500).send({error:“Server error”});
}
};
让parsedPath:string;
console.log(_target);//打印{},应为:{path://api/auth}
if(_target.path){
parsedPath=_target.path+path;
}否则{
parsedPath=path;
}
推({
路径:parsedPath,
答复,,
方法:“获取”,
});
};
}

我如何实现这个功能?

我在一个叫discord的家伙的帮助下解决了这个问题。对于将来遇到相同问题的人,以下是一个解决方案:

export function Controller(pathPrefix: string): ClassDecorator {
  return function (constructor: Function) {
    Object.entries(constructor.prototype["methods"]).forEach(
      ([_key, route]) => {
        const {
          func,
          method,
          path,
        }: {
          func: Function;
          method: "get" | "post" | "put" | "delete";
          path: string;
        } = <any>route;
        const response = async (
          req: Request,
          res: Response
        ): Promise<Response> => {
          try {
            return await func(req, res);
          } catch (e) {
            return res.status(500).send({ error: "Server Error" });
          }
        };
        routes.push({
          path: (pathPrefix || "") + path,
          response,
          method,
        });
      }
    );
  };
}

export function Get(path: string): MethodDecorator {
  return function (
    target: any,
    propertyKey: string | symbol,
    descriptor: PropertyDescriptor
  ): PropertyDescriptor {
    (target["methods"] = target["methods"] || {})[propertyKey] = {
      path,
      method: "get",
      func: descriptor.value,
    };
    return descriptor;
  };
}
导出函数控制器(路径前缀:字符串):ClassDecorator{ 返回函数(构造函数:函数){ Object.entries(constructor.prototype[“methods”]).forEach( ([_键,路由]=>{ 常数{ func, 方法,, 路径 }: { func:函数; 方法:“获取”|“发布”|“放置”|“删除”; 路径:字符串; }=路线; 常量响应=异步( 请求:, res:答复 ):承诺=>{ 试一试{ 返回等待功能(req,res); }捕获(e){ 返回res.status(500).send({error:“Server error”}); } }; 推({ 路径:(路径前缀| |“”)+路径, 答复,, 方法,, }); } ); }; } 导出函数Get(路径:string):MethodDecorator{ 返回函数( 目标:任何, propertyKey:字符串|符号, 描述符:PropertyDescriptor ):PropertyDescriptor{ (目标[“方法”]=目标[“方法”]| |{})[propertyKey]={ 路径 方法:“获取”, func:descriptor.value, }; 返回描述符; }; }
我在类decorator中添加了一个console.log,它在方法decorator之后记录。我该怎么办?Get decorator中的_target参数只是一个空对象。为什么呢?
export function Controller(pathPrefix: string): ClassDecorator {
  return function (constructor: Function) {
    Object.entries(constructor.prototype["methods"]).forEach(
      ([_key, route]) => {
        const {
          func,
          method,
          path,
        }: {
          func: Function;
          method: "get" | "post" | "put" | "delete";
          path: string;
        } = <any>route;
        const response = async (
          req: Request,
          res: Response
        ): Promise<Response> => {
          try {
            return await func(req, res);
          } catch (e) {
            return res.status(500).send({ error: "Server Error" });
          }
        };
        routes.push({
          path: (pathPrefix || "") + path,
          response,
          method,
        });
      }
    );
  };
}

export function Get(path: string): MethodDecorator {
  return function (
    target: any,
    propertyKey: string | symbol,
    descriptor: PropertyDescriptor
  ): PropertyDescriptor {
    (target["methods"] = target["methods"] || {})[propertyKey] = {
      path,
      method: "get",
      func: descriptor.value,
    };
    return descriptor;
  };
}