target.prototype is an empty object on class decorator

Viewed 658

I am trying to implement decorators with express (i dont want to download any package to do this). I wrote a Get decorator and a Controller decorator, following a guide. But the target in the controller decorator is an empty object.

Controller Decorator

export function Controller(prefix: string) {
  return function (target: Function) {
    for (let key in target.prototype) {
      const routeHandler = target.prototype[key];
      const path = Reflect.getMetadata("path", target.prototype, key);
      const method = Reflect.getMetadata("method", target.prototype, key);
      const middlewares = Reflect.getMetadata(
        "middlewares",
        target.prototype,
        key
      );

      if (path) {
        console.log("has path"); //never logs out
        router[method](`${prefix}${path}`, ...middlewares, routeHandler);
      }
    }
  };
}

Get Decorator

export function Get(path: string) {
  return function (target: any, key: string, desc: PropertyDescriptor) {
    Reflect.defineMetadata("path", path, target, key);
    Reflect.defineMetadata("method", "get", target, key);
  };
}
1 Answers

The methods/properties created through the class syntax are non-enumerable. Thus, you would need to use Object.getOwnPropertyNames() which returns an array of all properties (including non-enumerable properties)

Then in your case, you might want to convert your existing for loop into;

for(let key of Object.getOwnPropertyNames(target.prototype))

since now Object.getOwnPropertyNames return array.

Related