简体   繁体   中英

Cannot define nor retrieve metadata on method

I'm trying to attach a metadata key-value pair to an object key (method in a TS class), but no action is actually being performed on the element.

import 'reflect-metadata';

export const get = (path: string) => (target: any, key: string, desc: PropertyDescriptor) => {
  Reflect.defineMetadata('path', path, target, key);

  console.log(`path, target, key -> ${ path }, ${ target }, ${ key }`);
};


Snippet of the call section in the code

@controller('/auth')
export class LoginController {

  @get('/login')
  getLogin(req: Request, res: Response): void {/* method implementation */};
}

Controller iterating through methods metadata

export const controller = (routePrefix: string) => {
  return function (target: Function) {
    for (let key in target.prototype) {
      const routeHandler = target.prototype[key];

      const path = Reflect.getMetadata('path', target.prototype[key]);

      console.log('here is the path! -> ' + path);
      if (path)
        router.get(`${ routePrefix }${ path }`, routeHandler);
    }
  };
};

"debug" info

// Output
// [start:dev] path, target, key -> /login, [object Object], getLogin
// [start:dev] here is the path! -> undefined

Ok, solved. I was passing the wrong args to the Reflect.getMetadata method.

It was

Reflect.getMetadata('path', target.prototype, key);

instead of

Reflect.getMetadata('path', target.prototype[key]); // Wrong!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM