Obtain a reference to a class using a method decorator

My goal is to implement the following syntax:


@Controller('/user')
class UserController {
  @Action('/')
  get() {

  }

}

Now in the definition of decorators:

function Controller (options) {
 return  function(target: any) {
   let id = generateUniqueId();
   target.__id = id;
   addToSet(id, target)
 }

}

function Action (options) {
  return function (target: any, propertyKey: string) {
    //I need to retrieve the __id set in its class
  }
}

How can I access the unique id that I am assigning in the controller?

Answer №1

In order to ensure that method decorators are called before class decorators in TypeScript, I successfully implemented the following code:


  export function Controller(options: PathType | ControllerOptions): ClassDecorator {
    const {...controllerOptions} = mapOptions(options);
      return  function(constructor: Function) {
        const actions = [];

        Object.entries(constructor.prototype["methods"]).forEach(([_key, methodConfig]) => {
          console.info('_key', _key)
          console.info('methodConfig', methodConfig);
          actions.push(methodConfig);
        })
        controllerRegistery.add({
          controllerOptions,
          actions
        })
      }
  }


export class Methods {
    static GET(options) {
        return function( target: any,
          propertyKey: string | symbol,
          descriptor: PropertyDescriptor) {
            (target["methods"] = target["methods"] || {})[propertyKey] = {
              options,
              methodName: propertyKey,
              method: descriptor.value,
            };
            return descriptor;
        }
    }
}


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

Angular is throwing an error stating that the type '{ }[]' cannot be assigned to the type '[{ }]'

I'm in need of assistance and clarification regarding the error I encountered in my application... When I receive a JSON response from an API with some data that includes an array of products, I aim to extract these products (izdelki) from the array, ...

Combining and Filtering Arrays of Objects with Angular

I possess: arrayBefore arrayBefore = [{name:'n1', items: [i1]}, {name:'n2', items: [i2]}, {name:'n1', items: [i3]}] I desire to craft a function: myFunction myFunction(arrayBefore) In order for it to generate: arrayAfte ...

What is the best way to transpile TypeScript within the Astro framework?

Recently, I decided to dive into exploring Astro for a couple of upcoming projects. In my research, I delved into the script and typescript sections of the documentation (), as well as (). However, I found the workflow somewhat counterintuitive and struggl ...

Tips for creating an HTTP only cookie in NestJS

Currently, I am in the process of incorporating JWT authorization with both an accessToken and refreshToken. The requirement is to store these tokens in HTTP-only cookies. Despite attempting this code snippet, I have encountered an issue where the cookies ...

Converting JSON array to custom object array in TypeScript

As a newcomer to this area, please excuse any inaccuracies in my language. Don't hesitate to ask for more details if needed. I currently have some TypeScript interfaces: export interface Item { id: string type: string state: string } ex ...

Challenges with overwriting TailwindCSS classes within a React component library package

I just released my very first React component on NPM. It's a unique slider with fractions that can be easily dragged. Check it out here: Fractional Range Slider NPM This slider was created using TailwindCSS. During bundling, all the necessary classe ...

Encountering a TS2739 error while retrieving data in an Angular service function

In my code, I have created a function to fetch objects from my dummy data and assign them to a variable. setData(key: string) { let dataChunk: ProductIndex = PRODUCTDATA.filter(a => {a.productId == key;}); this.ProductData = dataChunk; } The i ...

Creating unique components with Angular2 and Ionic

Here is the HTML code for my custom component: <div> {{text}} {{percentLeft}} {{innerColor}} </div> And here is the TypeScript file for my component: import { Component, Input } from '@angular/core'; @Component({ selector: ...

Utilizing TypeScript's conditional return type with an object as a parameter, and incorporating default values

Is it possible to create a function where the return type is determined by a string, with some additional complexities involved? I'm looking to achieve the following: The parameter is contained within an object The parameter is optional The object it ...

Adding Google Tag Manager to a NextJS TypeScript project can be tricky, especially when encountering the error message "window.dataLayer is not

I am currently setting up GTM on my website, but I am facing a challenge as my NextJS project is in Typescript. I followed the example on Github provided by Vercel, but I encountered this error: TypeError: window.dataLayer is not a function Below is the c ...

Difficulty Converting Array of Objects to Proper Type with Q.Promise and KO.mapping

I have encountered an issue while trying to filter an observable array. It seems that the ko.utils.arrayFilter method is converting all my model's field names to lowercase, causing unexpected behavior. I should mention that this project involves Types ...

Retrieve the :id parameter from the URL as a numerical value in Node.js using Typescript

Is there a way to directly get the :id param from the URL as a number instead of a string in order to easily pass it on to TypeORM for fetching data based on a specific ID? Currently, I am using the following approach where I have to create an additional ...

Find a string that matches an element in a list

I currently have a list structured like this let array = [ { url: 'url1'}, { url: 'url2/test', children: [{url: 'url2/test/test'}, {url: 'url2/test2/test'}], { url: 'url3', children: [{url: & ...

Is it possible to extend the Object class in order to automatically initialize a property when it is being modified?

My experience with various programming languages leads me to believe that the answer is likely a resounding no, except for PHP which had some peculiar cases like $someArray['nonexistentKey']++. I'm interested in creating a sparse object whe ...

Creating unique random shapes within a larger shape on a canvas, as shown in the image

I have a parent rectangle and would like to add up to 10 or fewer rectangles on the right-hand side corner of the parent rectangle, as shown in the image below: I attempted to write code to achieve this, but the alignment is off-center from the parent rec ...

Encountering an Uncaught Error: MyModule type lacks the 'ɵmod' property

I am currently working on developing a custom module to store all my UI components. It is essential that this module is compatible with Angular 10 and above. Here is the package.json file for my library: { "name": "myLibModule", &qu ...

Is it possible to invoke a component's function within the click function of a Chartjs chart?

How do I trigger a function in my Component from an onclick event in my chart.js? export class ReportesComponent implements OnInit { constructor(public _router: Router, private data: ReporteService) {} this.chart = new Chart('myChart', { ...

I am encountering difficulties while attempting to import Typescript files. Upon compiling them into Javascript, I am faced with errors in the web browser, specifically the issue of "exports is not defined"

When I run TodoAppUI.js:15, I get an error saying "Uncaught ReferenceError: exports is not defined" In all my classes, I use the export keyword. For example: export class mysclass { public constructor(){} } Even though I have the proper syntax for impo ...

Can we determine the data type of an object based on a property within an interface?

Here is my current interface: MyInterface { prop1?: string, prop2?: string, } Now, I am looking to introduce an alternative property that mirrors the content of the existing properties but also infers if any properties are defined. For instance: ...

Encountering a NgForm provider error in Angular 4.4.6 development mode

UPDATE: Identifying the root of the issue has led me to search for a suitable solution. NOTE: This complication is specific to development mode (not production, and not utilizing AOT). The "Update" resolution I am implementing can be found here. In an a ...