What is the process behind the functioning of Typescript Annotation Scan?

I've been tackling a project that involves using annotations to implement routing for an express API app. However, I'm running into a problem where the route list is coming up empty at runtime.

Despite trying various resources, I haven't been able to figure out how to resolve this issue.

// RouteService File
export const routes: {
    path: string,
    router: string[]
}[] = [];

export function GetDynamicRoutes(): string[] {
  let router: string[] = [];
  routes.forEach(route => {
    router = router.concat(route.router);
  })
  return router;
}

// Decorators File
import { routes } from "../service/route.service";
import { AbstractController } from "../controller/abstract.controller";

export function Route(path: string) {
    return function (constructor: Function) {
        routes.push({
            path,
            router: constructor.prototype.router
        });
    }
}

export function RouteRequest(path?: string) {
    return function (target: Object, key: string | symbol,
        descriptor: PropertyDescriptor) {
        if (target.isPrototypeOf(AbstractController)) {
            const router = (target as AbstractController).router;
            const endpoint = path ? path : key.toString();

            router.push(endpoint);
        }
    }
}

// AbstractController file
export class AbstractController {
  public router: string[];

  constructor() {
    this.router = [];
  }
}

// TestController File
import { Route, RouteRequest } from "../decorator/route.decorator";
import { AbstractController } from "./abstract.controller";

@Route('test')
export class TestController extends AbstractController {
    @RouteRequest()
    helloWorld() {
        console.log('inside-hello-world');
    }
}

// Main File
import { GetDynamicRoutes } from "./service/route.service";

function main() {
    const routes = GetDynamicRoutes();
    console.log(routes);
}
main();

This code snippet provides guidance on how to implement dynamic routing in separate files with appropriate imports and decorators.

https://codesandbox.io/s/youthful-goldwasser-t8byo?fontsize=14&hidenavigation=1&theme=dark

Answer №1

In my recent experience, I encountered an issue with two primary questions in mind:

  1. How does Typescript Annotation Scan Work?
  2. What is the issue with my code?

To address the first question, it's essential to understand that decorator scanning always starts from the inside, following a top-to-bottom order.

@Class()
export class Sample {
  @property()
  testVar: string = "hi";

  @method()
  helloWorld() {
    console.log(this.testVar);
  }
}

In this example, the sequence of decorator execution is as follows:

  1. @property()
  2. @method()
  3. @Class()

You can explore a functional demo through this link:

https://codesandbox.io/s/xenodochial-forest-i2zz6?fontsize=14&hidenavigation=1&theme=dark

Turning to the next question at hand...

A helpful approach is to utilize a decorator scanner—a file that exports all files containing decorators for this specific purpose.

Resourceful Solution.

https://codesandbox.io/s/lively-meadow-houoj?fontsize=14&hidenavigation=1&theme=dark

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Improving database accuracy through addressing various referencing issues within the database

I am having some challenges with updating and saving new data from an HTML form to a database that contains references in Mongoose/Express. Specifically, I have a business model with a location reference to the location model. Below are the relevant code s ...

Tips for implementing index values in typescript within an Angular Material Table

<mat-cell *matCellDef="let element; let i index">{{ element.patientName }}<input type="hidden" [(ngModel)]="index" value={{i}}/></mat-cell> I created an index variable to access the value in the typescript f ...

When trying to refresh the page using react-router, the result is a blank page with the bundle.js not

I have encountered an issue where I am able to access all paths without any problems until I refresh the page. Upon refreshing, I am greeted with a blank page and no error messages. Despite searching for solutions related to this problem, none have seemed ...

Angular2 restricts Http requests within a specified time interval

I am a beginner with angular 2 and I have a value that is linked to user interaction that needs to be sent over http requests. The value can change multiple times per second, so I want to limit the http requests to one every 2 seconds during user interacti ...

Challenges Encountered When Running Angular 5 Karma Tests with Imports

Recently, I made the transition from Angular 2 to 5 for a project and encountered an issue where test cases related to compiling views started failing. Tests that were previously successful are now not working as expected. In order to troubleshoot the pro ...

Express router unable to transmit response to Httprequest

I'm having trouble getting a response from my express routes in the app.js file when trying to make an XMLHttpRequest. Can anyone help me figure out what's going wrong? Below is the code I have in two different files. File 1 function signup_dat ...

What could be the reason for encountering a SyntaxError due to an unexpected end of JSON input?

Here is the code snippet that I have developed using express and node.js: const express = require("express"); const https = require("https"); const app = express(); app.get("/", function(req, res) { ...

An issue has occurred: the property 'map' cannot be read as it is undefined

Encountered this unexpected error and struggling to understand the reason behind it.. I've been attempting to showcase events on angular-calendar: Error occurred in error_handler.ts:1 - ERROR TypeError: Cannot read property 'map' of unde ...

Is it possible to delete sessions using their specific session id?

Is there a way to easily delete sessions of blocked users? I currently store the session id in the user's document. How can I remove a user's session using their session id? session module : const session = require('express-session'); ...

What is the best way to exhibit information retrieved from my express server on the React frontend?

I've been working on connecting an Express backend with MySQL data and a React frontend for iterating through the information. While I haven't encountered any errors, nothing seems to display on React. What could be missing? The following code ...

Creating a specialized pathway with variable inputs within the URL

As a Node beginner, I am facing a challenge with an Express exercise on dynamic routes. The task at hand is to create a route that can accept dynamic arguments in the URL path and respond with a quote from the respective author. Here's a snippet of th ...

Error has occurred: Unanticipated symbol '.' detected in EJS-Lint

Seeking assistance with troubleshooting this issue. I recently began learning HTML and Node.js programming, and found it more challenging than expected. <!-- File name: index.ejs Author's name: Hae Yeon Kang (Lucy) web site name: Hae Yeon ...

Is there a more effective way to implement a Custom Validator using .forEach?

I have developed my own validation class as a learning exercise. Do you think this is an effective approach, or do you have suggestions for improvement? import { AbstractControl } from '@angular/forms'; export class ProjectNameValidator { pr ...

What is the best way to have a TypeScript function return a class?

Currently, I am utilizing TypeScript alongside a dependency injection library that functions quite similarly to Angular 1 - essentially, you register a factory with your dependencies as arguments. Here is an example of how I would register a class using E ...

Issues with onClick handler not functioning properly with Bootstrap button in ReactJS, Express.js, and React-Bootstrap stack

As I dive into learning ReactJS, I've encountered a stumbling block with the onClick handler. Following the Express.js application generator tutorial, my code looks like this. Could someone kindly point out what might be going wrong here? //app.j ...

Is it possible to configure the webpack --mode parameter with webpack-dev-middleware?

I have a server set up with Express that utilizes webpack-dev-middleware and webpack-dev-server. Recently, after upgrading to [email protected], I encountered the following warning: WARNING in configuration The 'mode' option has not been s ...

The index type cannot be 'undefined' in this context

I've been working on converting a JavaScript function to TypeScript, but I keep encountering the error message: Type 'undefined' cannot be used as an index type Although I understand that undefined cannot be used as an index, I have tried ...

Switching from dark mode to light mode when reloading or navigating to a new page

Hello everyone. I've successfully implemented a dark mode toggle on my website, but I'm facing an issue where the mode resets whenever I navigate to a new page or refresh the current page. Can anyone help me figure out how to prevent this from ...

The error message encountered is: "TypeError: Unable to access the 'apply' property of an undefined object within the

Currently in the process of developing a node js application with the integration of DHTMLX Scheduler feature on one of the pages. However, my progress is hindered by a recurring issue upon loading the page, resulting in the following error message: TypeE ...

I'm currently experiencing an issue where I am not receiving the Validation Flash Message in the UI. Instead, I am seeing a flash error displaying as [object Object],[object

I am currently developing a Blog application using NodeJs, where I have integrated express Validator to validate data. I am facing an issue with displaying flash messages in the UI after submitting forms. The error message that I receive is [object Object] ...