Encountering issues with utilizing Eeflector within a custom interceptor in NestJS. Module import error preventing functionality

I've been working on developing an interceptor for my NestJs application. My goal is to include some metadata in my controller method and then retrieve this data in my interceptor.

So, I created my interceptor along with a custom decorator to add the necessary metadata. However, I encountered an issue when attempting to access the Reflector in my interceptor constructor, resulting in an unsolved error.

Here is my interceptor code:

@Injectable()
export class MyCustomInterceptor implements CacheInterceptor {
  private reflector: Reflector;

  constructor(reflector: Reflector) {
    this.reflector = reflector;
  }

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const myReflectionData = this.reflector.get<string[]>('mykey', context.getHandler());
  //...

And here is my custom decorator:

import { applyDecorators, SetMetadata } from '@nestjs/common';

export const MyCustomDecorator = (listOfData: Array<string>) => applyDecorators(
  SetMetadata('mykey', listOfData),
);

  @MyCustomDecorator(['data1', 'data2'])
  @UseInterceptors(MyCustomInterceptor)
  @Get()
  async listMyData(
    @Query('limit') limit = 10,
    @Query('skip') skip = '',
    @Query('orderBy') orderBy = 'id',
    @Query('sort') sort = 'DESC',
  ) {
    // .....

When running this code, it results in the following error message:

[Nest] 10911  - 07/03/2022, 11:09:29 PM   ERROR [ExceptionHandler] Nest can't resolve dependencies of the MyCustomInterceptor (?). Please make sure that the argument Reflector at index [0] is available in the CommunitiesModule context.

Potential solutions:
- If Reflector is a provider, is it part of the current MyAppModule?
- If Reflector is exported from a separate @Module, is that module imported within MyAppModule?
  @Module({
    imports: [ /* the Module containing Reflector */ ]
  })

Error: Nest can't resolve dependencies of the MyCustomInterceptor (?). Please make sure that the argument Reflector at index [0] is available in the MyAppModule context.

Potential solutions:
- If Reflector is a provider, is it part of the current MyAppModule?
- If Reflector is exported from a separate @Module, is that module imported within MyAppModule?
  @Module({
    imports: [ /* the Module containing Reflector */ ]
  })

    at Injector.lookupComponentInParentModules (/.../node_modules/@nestjs/core/injector/injector.js:202:19)
    at Injector.resolveComponentInstance (/.../node_modules/@nestjs/core/injector/injector.js:157:33)
    at resolveParam (/.../node_modules/@nestjs/core/injector/injector.js:108:38)
    at async Promise.all (index 0)
    at Injector.resolveConstructorParams (/.../node_modules/@nestjs/core/injector/injector.js:123:27)
    at Injector.loadInstance (/.../node_modules/@nestjs/core/injector/injector.js:52:9)
    at Injector.loadProvider (/.../node_modules/@nestjs/core/injector/injector.js:74:9)
    at async Promise.all (index 8)
    at InstanceLoader.createInstancesOfProviders (/.../node_modules/@nestjs/core/injector/instance-loader.js:44:9)
    at /.../node_modules/@nestjs/core/injector/instance-loader.js:29:13

I attempted adding Reflector to both imports and providers in my .module.ts file, but unfortunately, it did not resolve the issue. How should I go about fixing this?

Any help would be greatly appreciated!

Answer №1

@Injectable()
export class CustomCacheInterceptor implements CacheInterceptor {
  constructor(private reflector: Reflector) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const cachedData = this.reflector.get<string[]>('mykey', context.getHandler());
  //...

Alternatively:

@Injectable()
export class CustomCacheInterceptor implements CacheInterceptor {
  @Inject() private reflector: Reflector;

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const cachedData = this.reflector.get<string[]>('mykey', context.getHandler());
  //...

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

What is the best way to access a class's private static property in order to utilize it for testing purposes?

Hello, I am currently a beginner in TypeScript and unit testing, so this inquiry may seem elementary to those more experienced. I am attempting to perform unit testing on the code provided below using sinon. Specifically, I am interested in testing whethe ...

How to display an [object HTMLElement] using Angular

Imagine you have a dynamically created variable in HTML and you want to print it out with the new HTML syntax. However, you are unsure of how to do so. If you tried printing the variable directly in the HTML, it would simply display as text. This is the ...

I'm receiving an error message stating "mongoose.connect is not a function" while attempting to establish a connection with mongoose. Can you help me troub

I'm a beginner in Node.js and I'm currently working on creating a node/express/mongoose server app using TypeScript. Below is my app.ts file: // lib/app.ts import express from 'express'; import * as bodyParser from 'body-parser&a ...

The negation operator in Typescript is failing to negate as expected

When a user changes a multiselect element, there is a function that runs to control the visibility of an error message: getVisibility(multiselect) { if ((multiselect.selectedCategories.length < 1 && !multiselect.allSelected) && th ...

Access to this feature is restricted when using a decorator in TypeScript with NodeJS

I have designed a decorator to handle async errors, but I am encountering difficulties in accessing it within class methods. My goal is to develop a reusable CRUD class that other classes can inherit from, with a method for CRUD operations. Decorator Code ...

Troubleshooting Typescript compilation using tsc with a locally linked node package

In our project using React/React Native with Typescript, we have a mobile app built with React Native and a shared private package that is utilized by both the React Native client and the React frontend. Due to frequent changes in the shared package, we a ...

The ajv-based middy validator does not adhere to the specified date and time format

When it comes to validation, I rely on middy as my go-to package, which is powered by ajv. Below is an example of how I set up the JSON schema: serviceDate: { type: 'string', format: 'date-time' }, The structure o ...

What is the best way to fill the dropdown options in every row of a data table?

This HTML snippet displays a data table with test data and corresponding dropdown options. <tr> <th> Test Data </th> <th> Test Data ...

Discover the process of retrieving all workday dates using Angular

Currently, I am working on a project in Angular that involves allowing employees to record their work hours. However, I am facing a challenge in figuring out how to gather all the work dates and store them in an array. Here is what I have attempted so fa ...

What is the solution to the error message "Unable to assign property of undefined"?

I am currently working on an angular countdown timer and encountering a TypeError when attempting to access a variable from another component. I am struggling to identify the root cause of this issue. Here is the video tutorial that I am using as a referen ...

"Firebase function fails to return Typescript class variable, resulting in 'undefined'

Being someone with a background in python/golang, I am now delving into ionic2. There seems to be an issue that I can't quite figure out due to my current level of knowledge in this stack. Perhaps I just need a way to reference the outer scope of this ...

TypeScript: Defining an Array Type within a Namespace or Module

Within a specific namespace, I have the following code: const operation1 = Symbol("operation1"); const operation2 = Symbol("operation2"); export interface Array<T> extends IConjable<T>, ISeqable<T> {} Array.prototype[op ...

Displaying errors to the user using Angular's HttpClient in an Ionic application

I am currently working on a small project and struggling to grasp certain TypeScript concepts. Specifically, I am trying to pass data from a form to an object and then send it via an HTTP service to an endpoint. The response is displayed in the console, in ...

Creating a Typescript version of the mongodb project aggregation functionality

Present scenario: I am currently working on creating a type-safe wrapper for the node-mongodb driver. I am facing challenges in determining the return type for the project aggregation stage. Feel free to check out the TypeScript Playground here class Base ...

Angular 2 Express failing to trigger ngOnInit method

I'm having some trouble with Angular services. I used the default code from "Angular.io" to make service calls, but for some reason the ngOninit method isn't getting called. I've implemented the component from OnInit and added @Injectable to ...

Chrome stack router outlet and the utilization of the Angular back button

I'm experiencing an issue with the back button on Chrome while using Angular 14. When I return to a previous page (URL), instead of deleting the current page components, it keeps adding more and more as I continue to press the back button (the deeper ...

How to ensure Angular mat-button-toggle elements are perfectly aligned within their respective groups

https://i.stack.imgur.com/Wjtn5.png Hello there, I'm trying to make the numbers in the first group match the style of the second group (noche, mañana...). I've set both the group and individual element width to 100%, but the numbers beyond 22 ...

Importing Heroicons dynamically in Next.js for more flexibility

In my Next.js project, I decided to use heroicons but faced a challenge with dynamic imports. The current version does not support passing the icon name directly to the component, so I created my own workaround. // HeroIcon.tsx import * as SolidIcons from ...

Can someone point me to the typescript build option in Visual Studio 2019 Community edition?

When I created a blank node.js web app on VS 2015, there was an option under project properties called "TYPESCRIPT BUILD" that allowed me to configure settings like combining JavaScript output into a single file. After upgrading to VS 2019 Community, I ca ...

The upload function does not allow re-uploading of a file that has been previously deleted

Attempting to upload a file using the following code onDrag(event:any) { console.log(this.toUpload); if(this.toUpload.length >0){ this.error = "Only one file at a time is accepted"; }else{ let fileName = event[0].name; let split ...