0

I am trying to learn typescript and in my course, there is a section where my tutor is trying to create a class for login controller and I am trying to use decorators to create some kind of modular structure.

Now, what is my problem? I create decorators for my class on top of all decorators. The purpose of this decorator is to iterate on the properties of the prototype object of this login controller class. the problem I counter is when I am trying to iterate on the prototype object there is no property to be found. But if I try to call each property directly I can access to them.

I need a way to loop on the properties of prototype object of the selected class

I tried looping on the prototype object like this:

export const controller = (pathPrefix: string) => {

    
    return function (target: Function) {

         for (const key in target.prototype) {
           const routeHandler = target.prototype[key];
           const path = Reflect.getMetadata("path", target.prototype, key );
           if (path) {
             controllerRoute.get(`${pathPrefix+path}`, routeHandler)
           } 
         }
    }
}

It didn't work. The compiler didn't implement for loop block. I tried to call the property directly like this:

return function (target: Function) {
        
        console.log("hello", target.prototype);

        const routeHandler = target.prototype["getLogin"];
        const path = Reflect.getMetadata("path", target.prototype, "getLogin");
        if (path) {
            controllerRoute.get(`${pathPrefix+path}`, routeHandler)
        }
    }

It's working but the problem is the code is hard coded.

The class I am trying to use decorators in it is:

@controller("/auth")
 class LoginController {

 @get("/login") 
  getLogin(_: unknown, res: Response): void {
  res.send(`
  <form method="POST">
  <div>
  <label for="email">Email</label>
  <input name="email" type="email" />
  </div>
  <div>
  <label for="password">Password</label>
  <input name="password" type="password" />
  </div>
  <button type="submit"> Login </button>
  </form>
  `);
 };
}
Farbod Shabani
  • 422
  • 4
  • 9

0 Answers0