When working with interceptors in NestJS (view documentation), I encountered a situation where I needed to call a service within the interceptor. Here is the approach I took:
export class HttpInterceptor implements NestInterceptor {
constructor(private configService:ConfigService){}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
let request = context.switchToHttp().getRequest();
const apikey= this.configService.get('apikey');
const hash=this.configService.get('hash');
request.params= {apikey:apikey ,hash:hash,ts:Date.now()}
return next
}
}
This is how the ConfigService looks like:
export class ConfigService {
private readonly envConfig: { [key: string]: string };
constructor(filePath: string) {
this.envConfig = dotenv.parse(fs.readFileSync(path.join(__dirname, filePath)));
}
get(key: string): string {
return this.envConfig[key];
}
}
Unfortunately, when trying to use the ConfigService
within the interceptor, I encountered an error message indicating that the service was undefined:
Cannot read property 'get' of undefined
I have verified that I have correctly instantiated the ConfigService
, so I am puzzled as to why it cannot be accessed within the interceptor.