Requirements for Method Decorators - The complete path of the class module using the decorator must be provided

Upon running the decorator (method decorators) function, we are provided with access to target, methodName, and descriptor.

I am seeking the module path for target in this specific scenario. Essentially, I want the file path that points to the module that invoked the decorator. How can I retrieve this data?

I attempted utilizing the module object, specifically module.parent.filename, but it proved unreliable as it does not update when the same decorator is employed in another file - preserving the details of the initial call location of the decorator.

Answer №1

If you are considering utilizing the Reflect API, there is a specific approach you must follow. Initially, it is essential to store the module information for the target class as metadata in a class decorator before accessing it in your method decorator.

UPDATE:

My initial solution turned out to be more complex than anticipated; I overlooked the fact that method decorators are evaluated prior to class decorators, requiring a workaround.

decorators.ts

import "reflect-metadata";

export function InjectModuleInfo (filename: string) {
    return function <T extends { new (...args: any[]): {} }> (constructor: T) {
        Reflect.defineMetadata("modulePath", filename, constructor);
    }
}

export function MyMethodDecorator (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    console.log(Reflect.getMetadata("modulePath", target.constructor));
}

TestClass.ts

import {MyClassDecorator, MyMethodDecorator} from './decorators';

@InjectModuleInfo(__filename)
class BaseClass {}

export class TestClass extends BaseClass {
    @MyMethodDecorator
    public myMethod () {}
}

For each class where this functionality is required, inheritance from a base class with the attached module info as metadata is necessary. Without this, if you directly apply the decorator to TestClass, the class decorator may not be processed in time for the method decorator.

Answer №2

After some research, I was able to utilize the callsites package to pinpoint the origin of a specific call. By applying my custom query, I can sift through and extract the correct path.

Here's an example:

const desiredPath: string = callsites()
  .find(site => site.getFileName().includes('myquery'))
  .getFileName();

It's a fairly straightforward solution that effectively resolves my issue.

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

Remove the user along with all of their associated documents from Firestore

When a user wants to delete their account, I need to ensure that the 'documents' they created in Firebase are deleted as well. After some research online, I came across the following code snippet: deleteAccount() { const qry: firebase. ...

Having trouble retrieving information from combineLatest in Angular?

I'm having some trouble with fetching files to include in the post logs. It seems that the data is not being passed down the chain correctly when I attempt to use the pipe function after combining the latest data. This code snippet is part of a data r ...

Implement the TypeScript handleChange function for input fields and dropdown menus

Currently, I am in the process of developing a form using TypeScript and Material-UI components. My objective is to create a change handler function that can be utilized for both select and textfield changes. Below are my state and functions: const [re ...

Guide to setting the order of rendering in React applications

I am currently working with a .tsx file that renders two components: export default observer(function MyModule(props: MyModuleProps) { .... return ( <div> <TopPart></TopPart> <LowerPart>< ...

What's the best way to process a string array using iteration in Typescript?

I have an array of colors: colors = ['red','blue','purple']; I would like to display the following message: colors in ('red','blue','purple') When I tried to achieve this using forEach metho ...

What is the best way to create an assertion function for validating a discriminated union type in my code?

I have a union type with discriminated properties: type Status = { tag: "Active", /* other props */ } | { tag: "Inactive", /* other props */ } Currently, I need to execute certain code only when in a specific state: // At some po ...

invoking an API within a map function and utilizing the response

vm.owners = parents.children.map(function(e) { getparentById(e.Id) .then(function(getresponse) { var parentLink = '<a href="/#/parent/onboard/' + e.Id + '" target="_blank">' + e.Number + "-&qu ...

Typescript: Why Lines Are Not Rendering on Canvas When Using a For-Loop

What started out as a fun project to create a graphing utility quickly turned into a serious endeavor... My goal was simple - to create a line graph. Despite my efforts, attempting to use a for-loop in my TypeScript project resulted in no output. In the ...

Exploring the process of retrieving data from localStorage in Next.js 13

Having recently delved into the realm of Next JS, I've encountered a hurdle when it comes to creating middleware within Next. My aim is to retrieve data from local storage, but I keep hitting roadblocks. middleware.ts import { key, timeEncryptKey, to ...

The issue of "ReferenceError: Cannot access '<Entity>' before initialization" occurs when using a OneToMany relationship with TypeORM

There are two main actors involved in this scenario: User and Habit. The relationship between them is defined by a OneToMany connection from User to Habit, and vice versa with a ManyToOne. User Entity import {Entity, PrimaryGeneratedColumn, Column, Creat ...

Ways to determine if a date matches today's date within a component template

I am currently displaying a list of news articles on the webpage and I want to show the word "Today" if the news article's date is equal to today's date. Otherwise, I want to display the full date on the page. Is there a way to compare the news.D ...

React 18 Fragment expressing concern about an excessive amount of offspring

Recently, I attempted to integrate Storybook into my React application, and it caused a major disruption. Despite restoring from a backup, the absence of the node_modules folder led to issues when trying 'npm install' to recover. Currently, Types ...

Tips for generating a subject in rx.js while utilizing 2 parameters

Within my Angular2 application, I am utilizing a communication service to handle interactions between components. When calling the method: this.notification.create('test'); The service structure is as follows: export class NotificationServic ...

When using Angular 2, an error may occur where you receive a message stating that you cannot read the property 'length' of undefined while attempting to call

When creating a component (let's call it A) with the @input decorator to retrieve values from the selector, keep in mind that this component will generate text fields based on the input values specified in the selector. Component A is then utilized in ...

Using the useRef validation can lead to errors when trying to reference the current value against an input

Currently, the code is functioning well but an error alert from Typescript needs to be addressed. A warning pops up regarding the use of ref.current.value. ERROR 1. TS18048: 'ref.current' is possibly 'undefined'. To tackle this issue, ...

Printing values of an object in an Angular/HTML script is proving to be quite challenging for me

In my Angular project, I have created a service and component for listing objects. The list is functioning correctly as I have tested it with 'console.log()'. However, when I try to display the list on localhost:4200, nothing appears. <table&g ...

Using TypeScript - Implementing a generic constraint to allow passing a Zod schema result as an argument to a function

I'm in the process of creating a custom controller function to streamline my application. The repetitive task of wrapping try-catch, parsing a zod schema, and merging the request zod schema into a single object is present in all handler functions. The ...

Subscribing to valueChanges in reactive forms to dynamically update checkbox options

My goal is to create a select dropdown with options for bmw, audi, and opel. The user can only select one option from the dropdown, but they should also have the ability to select the options that were not chosen using checkboxes. cars = [ { id: 1, na ...

Transferring 'properties' to child components and selectively displaying them based on conditions

This is the code for my loginButton, which acts as a wrapper for the Button component in another file. 'use client'; import { useRouter } from 'next/navigation'; import { useTransition } from 'react'; interface LoginButtonPr ...

Leverage the exported data from Highcharts Editor to create a fresh React chart

I am currently working on implementing the following workflow Create a chart using the Highcharts Editor tool Export the JSON object from the Editor that represents the chart Utilize the exported JSON to render a new chart After creating a chart through ...