I had created on Interceptor in the module. I want to get repository [LocumRepository] in the Interceptor and put some processing after the call. Following is my Intercepter class:
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { LocumEntity } from '../../locum/entities/locum.entity';
import { getRepository, Like, Repository } from 'typeorm';
import { Observable, combineLatest } from 'rxjs';
import { tap } from 'rxjs/operators';
import { map } from 'rxjs/operators';
@Injectable()
export class ApprovalInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next
.handle()
.pipe(
map(value => this.updateLocumStatus(value, context))
);
}
async updateLocumStatus(value, context) {
if (context.switchToHttp().getResponse().statusCode) {
let locumData = await getRepository(LocumEntity)
.createQueryBuilder('locum')
.where('locum.id = :id', { id: value.locumId })
.getOne();
}
return value;
}
}
I am receiving following error:
No repository for "LocumRepository" was found. Looks like this entity is not registered in current "default" connection?
while LocumRepository declared in the module file and I am using it out side the Interceptor class
As an interceptor
is @Injectable()
you could take the DI approach and inject it as you normally would using @InjectRepository(Locum)
(or whatever your entity is called), and then do the usual service this.repo.repoMethod()
. This way, you also still get the benefits of using DI and being able to provide amock during testing. The only thing to make sure of with this approach is that you have this repository available in the current module where the interceptor will be used.