Learn how to set up a class using TypeScript decorators

Is there a way to automatically initialize a class when a specific decorator is present above the class? For example:

@apiController
export class usersControllers extends lib.baseClasses.apiControllerBase().apiController {
    @lib.decorators.routesRegister().register({ "url": "/login","isLoginUrl":true})
    public postLoginUser($data) {
        let userDetails = {
            name: 'John Doe',
            userType: '1', // required
            age: '30',
            tokenExpiry:5000000 // required
        };

        setTimeout(() => {
            this.ok(userDetails);
        }, 100);

        return this.promise;
    }
}

In the given example, I want the @apiController decorator to automatically initialize the class. Can anyone assist me with resolving this issue?

Answer №1

One way to approach this situation would be:

function initiateApi(target: any) 
{
    let object = new target.constructor();
}

UPDATE: In order to ensure that decorators are activated, I have come up with a clever technique. Simply add a dummy function within the same module like so:

export function ActivateDecorators() { } 

Then, just invoke this function within your initialization routines or system. This simple action will trigger all decorators in that module.

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

Can a "fragile export" be generated in TypeScript?

Testing modular code can be challenging when you have to export things just for the purpose of testing, which can clutter your code and diminish the effectiveness of features like "unused variable" flags on compilers or linters. Even if you remove a usage ...

Angular fails to show route after successful login

Within my application, I have divided it into two areas: the admin area (referred to as iwti) and the 'retaguarda' area. The 'retaguarda' section is functioning correctly, but when I navigate to the route /iwti, the layout within the &l ...

Dropdown Pattern with React CTA Modal

While using MaterialUI's ButtonGroup for a dropdown menu, I encountered an issue trying to set up a series of CTAs that are easily interchangeable within it. The goal is to have all components reusable and the choices in the dropdown dynamic. const C ...

Creating a custom data type for the Tanstack table filtering function

I developed a unique filter function specifically for enhancing the functionality of Tanstack Table by utilizing fuse.js. Despite my efforts, TypeScript consistently raises concerns when I try to define the type for my custom function. My goal is to alig ...

Utilizing Azure Function Model v4: Establishing a Connection with Express.js

Using Model v4 in my Azure function index.ts import { app } from "@azure/functions"; import azureFunctionHandler from "azure-aws-serverless-express"; import expressApp from "../../app"; app.http("httpTrigger1", { methods: ["GET"], route: "api/{*segme ...

What is the abbreviation for indicating a return type as nullable?

Is there a way to use shorthand for nullable return types in TypeScript similar to using "name?: type" for parameters? function veryUsefulFunction(val?: string /* this is OK */) // but not this or other things I've tried. // is there a way a ...

Instead of showing the data in the variable "ionic", there is a display of "[object object]"

Here is the code snippet I'm working with: this.facebook.login(['email', 'public_profile']).then((response: FacebookLoginResponse) => { this.facebook.api('me?fields=id,name,email,first_name,picture.width(720).height( ...

I'm looking for a way to implement a jQuery-style initialization pattern using TypeScript - how can I

My library utilizes a jQuery-like initialization pattern, along with some specific requirements for the types it should accept and return: function JQueryInitializer ( selector /*: string | INSTANCE_OF_JQUERY*/ ) { if ( selector.__jquery ) return select ...

Refreshing the page causes the Angular/Ionic Singleton instance to be destroyed

I have a TypeScript singleton class that is responsible for storing the login credentials of a user. When I set these credentials on the login page and navigate to the next page using Angular Router.navigate (without passing any parameters), everything wor ...

Properties for a standard React component

Currently, I am developing a form component in react with typescript that requires a 'fieldStructures' and an 'onSubmit' prop. type FieldStructure { type: 'text'; name: string; label?: string; helpText?: string ...

Retrieving the value from a string Enum in Angular based on an integer

export enum RoleTypesEnum { RoleA = 'Role is A', RoleB = 'Role is B', } // in TypeScript file public RoleTypesEnum = RoleTypesEnum; I am trying to obtain the string value (e.g. Role is B) from an enum using an integer. If I u ...

Having trouble verifying the selection option in Angular 6

I've been trying to implement Select option validation in Angular 6, but neither Aria-required nor required seem to be effective. The requirement is for it to display a message or show a RED border similar to HTML forms. Here's the HTML snippet ...

In fact, retrieve the file from an S3 bucket and save it to your local

I've been attempting to retrieve an s3 file from my bucket using this function: async Export() { const myKey = '...key...' const mySecret = '...secret...' AWS.config.update( { accessKeyId: myKey, secretAcces ...

What is the best way to merge two approaches for tallying items within each category?

I have an Angular 8 application that includes two methods for displaying the number of items in each category. These items are retrieved from the back-end and are categorized as follows: <mat-tab> <ng-template mat-tab-label> ...

Exploring NestJS: Leveraging the @Body() Decorator to Retrieve Request Body Data

import { Controller, Post, Body } from '@nestjs/common'; import { MyService } from 'my.service'; import { MyDto } from './dto/my.dto'; @Controller('my-route') export class MyController { constructor(private rea ...

Opt for ion-select with a range of i to j options

Looking to set up an ion-select menu in Ionic4 where users can pick a value between 20 and 220 without manually typing each number. I attempted to use the approach detailed in this post Tersest way to create an array of integers from 1..20 in JavaScript ...

The MUI DataGrid's onCellEditStop event triggers when a cell's value is

When using MUI DataGrid, I encountered an issue where the value of a previously edited cell changes when editing another cell. I read that using onCellEditCommit as a solution, but since it's deprecated, I'm seeking an alternative fix. const ha ...

The initial invocation of OidcSecurityService.getAccessToken() returns null as the token

Our internal application requires all users to be authenticated and authorized, including for the home page. To achieve this, we use an HttpInterceptor to add a bearer token to our API requests. Initially, when rendering the first set of data with the fir ...

What determines the narrowing of a type when it is defined as a literal versus when it is returned from a function?

I'm really trying to wrap my head around why type narrowing isn't working in this scenario. Here's an example where name is successfully narrowed down: function getPath(name: string | null): "continue" | "halt" { if (n ...

Angular's getter value triggers the ExpressionChangedAfterItHasBeenCheckedError

I'm encountering the ExpressionChangedAfterItHasBeenCheckedError due to my getter function, selectedRows, in my component. public get selectedRows() { if (this.gridApi) { return this.gridApi.getSelectedRows(); } else { return null; } } ...