Search code examples
typescripttypescript-decoratorloopback4

How do Decorators for Configuration/Route Mapping work (TypeScript & Loopback4)?


In Loopback4 REST Endpoints/Operations like "GET /greet" are mapped/configured with a Decorator above the method that processes the query and returns the result:

 @get('/greet', spec)
  greet(name: string) {return "hello"}

I am completely new to Loopback and Typescript. My question is how do such configuration Decorators work in general (also in other frameworks)?

Some Detailed Questions:

  • Are the decorators processed at build time and some configuration code is generated out of them? Or are they only processed at runtime?
  • If they are processed at runtime, I understand the case, that a decorator will be triggered if the method is called, that is obvious. But here the decorator contains information that needs to be configured in the system before it even gets or can be triggered, so the system knows how to call this method. How does this work? Is there a function in TypeScript that returns an Array of all Decorators?
  • ...

Thanks very much!


Solution

  • They are evaluated at build-time and require the experimentalDecorators: true setting in tsconfig.json to enable them.

    The TypeScript docs cover them well here: https://www.typescriptlang.org/docs/handbook/decorators.html