Steve
Steve

Reputation: 286

Dependency Injection for Nest JS Interceptor is Undefined

I have created an interceptor as shown below that I wish to use globally. I added the interceptor to my module and set it up so that nest js should handle the DI for me per NestJS Docs, however when I make a request to my service, I get an error indicating Cannot read property log of undefined so it appears that the DI is not being taken care of by NestJS.

Interceptor Code:

import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { LoggingService } from './logging.service';

@Injectable()
export class AuthInterceptor implements NestInterceptor {
  constructor(private readonly loggingService: LoggingService) { }
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next
      .handle()
      .pipe(
        map((response) => {
          this.loggingService.log('Responded successfully');
          return response;
        })
      );
  }
}

Interceptor Module:

import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { AuthInterceptor } from './auth.interceptor';
import { LoggingService } from './logging.service';

@Module({
  providers: [
    LoggingService,
    {
      provide: APP_INTERCEPTOR,
      useClass: AuthInterceptor,
    },
  ],
})
export class AuthInterceptorModule {}

My app.module.ts at the root of my application imports the AuthInterceptorModule. I am assuming I am messing something up but it is not clear to me how to fix this DI issue.

Upvotes: 6

Views: 9482

Answers (1)

Steve
Steve

Reputation: 286

I was able to resolve this one on my own after finding that my LoggingService relied on another dependency that was request scoped. Since there was a request scoped dependency in my interceptor, this meant that my interceptor also had to be request scoped.

The change to the code was simple and only required that I change the AuthInterceptorModule from:

import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { AuthInterceptor } from './auth.interceptor';
import { LoggingService } from './logging.service';

@Module({
  providers: [
    LoggingService,
    {
      provide: APP_INTERCEPTOR,
      useClass: AuthInterceptor,
    },
  ],
})
export class AuthInterceptorModule {}

to

import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR, Scope } from '@nestjs/core';
import { AuthInterceptor } from './auth.interceptor';
import { LoggingService } from './logging.service';

@Module({
  providers: [
    LoggingService,
    {
      provide: APP_INTERCEPTOR,
      scope: Scope.REQUEST,
      useClass: AuthInterceptor,
    },
  ],
})
export class AuthInterceptorModule {}

Upvotes: 12

Related Questions