Why is the method developer executed before the class is instantiated?

Asked

Viewed 30 times

1

I was investigating about using decorators on nodejs express routers, and found the following turorial How to make REST API’s using Node.js, Express.js & Typescript Decorators

Analyzing the code, I realized that the Users controller class (Users.controller.ts) receives the Developer @routesDecorator in one of its method and the same is imported into the server.ts however is not instantiated. Running the entire project is functional, but I don’t understand why.

Users.controller.ts

import { Request, Response } from 'express';
import routesDecorator from '../decorators/routes.decorator';

export class Users {
    @routesDecorator({
        path: '/users',
        method: 'get'
    })
    getUsers(req: Request, res: Response) {
        res.send('Typescript Decorators are awesome !!!');
    }
}

Routes.decorator.ts

import { Router } from 'express';
export const appRouter = Router();

interface IOptions {
    path: string;
    method: 'get'| 'post'| 'put' | 'delete' ;
    middlewares?: any[],
}

function routesDecorator(options: IOptions) {
    return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
       (appRouter as any)[options.method](options.path, target[propertyKey]);
    };
}

export default routesDecorator;

server.ts

import * as express from 'express';
const app = express();
import './controllers';
import { appRouter } from './decorators/routes.decorator';

app.use(appRouter);app.listen(3000,()=>{
    console.log('Server is running on port 3000');
});

Would it be some go Horse that has been leveraged post typescript transpilation, or is it a default behavior?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.