Gathering up all the embellishers

Is it viable to access all decorators located in a specific directory? I am interested in developing a routing component that functions similarly to Symfony, which utilizes Annotations:

@Route("/")
public function index() { // ...

Therefore, when initializing my application, I aim to identify all annotations and generate routes based on them. Is this achievable?

edit: To elaborate further: My focus is on a NodeJS application. I intend to scan through every file within a given directory and detect all decorators present.

Answer №1

To handle this situation, you will first need to locate and access the files using the fs module. From there, you can either manually parse the files or utilize the Compiler API. Both options may not be very enjoyable tasks.

Another approach (assuming I am understanding your context correctly) is to register each component that invokes the decorator with a setup like this:

const REGISTRY = new Map<string, Function[]>();
export function Route(path: string) {
    if (!REGISTRY.has(path)) {
        REGISTRY.set(path, []);
    }

    return (constructor: Function) => {
        REGISTRY.get(path).push(constructor);

        // Perform the operations of the decorator here
    }
}

If the Route decorator does not originate from your code but instead belongs to a third-party library, consider creating your own decorator that can invoke the original one.

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

Converting an object into a list of lists using Typescript

When making an API call from Angular 5, the response is returned in the following format. { "metadata":{ "lastSyncTime":"2000-11-21T16:07:53", "dataFromDB":true }, "allocationReports":[ ...

Transpilation appears to dissect a function

I've encountered a strange issue where the transpiler is splitting a single method into two parts: Before transpiling: MemberSchema.methods.addAccount = (account: IAccount): void => { this.account = new Account({ ...account, i ...

Invoke a function in an object based on a specified property dynamically

I have a component that receives parameters and needs to call dynamic functions provided in the params. The challenge is that these functions are dynamic, so they need to be defined before being passed. Here is an example of the parameters that can be pas ...

Managing asynchronous promises in Ionic 2: Queuing storage requests

I'm currently working on an app using Ionic 2 and incorporating the Ionic Native Storage plugin to store key-value pairs. To address potential concurrency problems, I am looking into queuing the storage calls. For instance, I have functions like save ...

Looping through NavItems component using JavaScript or Angular

My Angular project includes a navbar component with an app sidebar that has a navItems attribute. Below is the content of my navBar: <app-header style="background-color : #e65100;" [fixed]="true" [navbarBrandFull]="{ src: &a ...

Oops! Make sure to explicitly allow the dependency @types/html2canvas by adding it to the "allowedNonPeerDependencies" option

After installing the html2canvas package in my Angular library project, I encountered an error when compiling in production mode using the command ng build --prod. The specific error message is as follows: ERROR: Dependency @types/html2canvas must be exp ...

Change the keys of the object in the return statement

Scenario Imagine a scenario where a method called matter is returning an object in the form of return {content, data} Issue There is a conflict when the method is called a second time, as it overwrites any previous variables that were set from the return ...

Adding a component to a page in Angular 4: A step-by-step guide

Currently engaged in a project that involves creating a mobile application design within a web application. I'm wondering how to display my Component object on a page using ViewChild? I have a list of PageComponents, below is the PageComponent class ...

How can Jest be configured to test for the "permission denied" error?

In my Jest test, I am testing the behavior when trying to start a node http server with an invalid path for the socket file: describe('On any platform', (): void => { it('throws an error when trying to start with an invalid socket P ...

Tips for sending the image file path to a React component

Hey, I'm working on a component that has the following structure: import React from "react"; interface CInterface { name: string; word: string; path: string; } export function C({ name, word, path }: CInterface) { return ( < ...

The for loop displays only the most recent data fetched from Firebase

When using a for loop to retrieve a user's progress, I encounter an issue. In Typescript: this.userProgress = af.object('/UserProgress/' + this.currentUser + '/', { preserveSnapshot: true }); this.userProgress.subscribe(snaps ...

Dealing with asynchronous operations in a pipeline with fp-ts

I'm currently exploring fp-ts and have been contemplating how to restructure my functions in order to steer clear of nested folds. While many online examples showcase a clean invocation of the pipe function, I am struggling to eliminate the nested fol ...

Typescript HashMap implementation with Lists as values

Currently delving into TypeScript, I am attempting to generate a collection in a manner akin to the following Java example: HashMap<String, List<String>> hashMap = new HashMap<String,List<String>>(); Struggling to locate any releva ...

Getting information from the firebase database

I'm currently working on a web application that utilizes Firebase database. I'm encountering difficulties when trying to access the elements that are labeled as encircled. Can anyone offer any guidance or suggestions? Here is the code snippet I& ...

NextJS API routes consistently provide a status code of 200 upon execution

I am new to the concepts of Next.js, and I recently encountered an issue while attempting to fetch data from an API. The API is designed to check if a user session exists (i.e., if the user is logged in) and then returns a JSON response through a GET reque ...

The type 'elementfinder' cannot be assigned to a parameter of type 'boolean'

Currently, I am working on a function that checks if a checkbox is selected. If it's not checked, then the function should click on it. However, I encountered an error message stating "argument of type 'elementfinder' is not assignable to pa ...

What is the best way to implement bypassSecurityTrustResourceUrl for all elements within an array?

My challenge is dealing with an array of Google Map Embed API URLs. As I iterate over each item, I need to bind them to the source of an iFrame. I have a solution in mind: constructor(private sanitizer: DomSanitizationService) { this.url = sanitizer. ...

Dealing with Unexpected Timeout Errors and Memory Leaks in Express/Typescript Using Jest, Supertest, and TypeORM

Currently, I am in the process of writing unit tests for an express API. Each test suite initiates a fresh instance of an express server before running the tests. Individually, each test suite runs smoothly without any problems. However, when executed tog ...

Utilizing Typescript's pattern matching for subtypes of string literal types

export interface Action{ type: string; } export interface LoadTodos { type: "LOAD_TODOS_ACTION" } export interface AddTodo { type: "ADD_TODO_ACTION", todo: Todo } export type KnownAction = LoadTodos | LoadTodosSucce ...

Converting an array of strings to IDropdownOption in TypeScript and vice versa

In my TypeScript code snippet, I have defined two functions: getstringArray1DropdownOption and getstringArray2DropdownOption to handle dropdown options. function getstringArray1DropdownOption(stringArray1Text: string): IDropdownOption { return { ...