1
votes

After configured cache globally like the docs, the CacheInterceptor throws an error if i use it outside the app.module.

app.module.ts

const cacheConfig = {
  store: redisStore,
  host: 'localhost',
  port: 6379
}

@Module({
  imports: [
    CacheModule.register(cacheConfig),
    CustomerModule,
  ],
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: CacheInterceptor
    }
  ]
})
export class AppModule {}

customer.module.ts

@Module({
  imports: [TypeOrmModule.forFeature([CustomerRepository]), TypeOrmModule.forFeature([User])],
  controllers: [CustomerController]
})
export class CustomerModule {}

customer.controller.ts

@Controller('customer')
export class CustomerController {
  constructor(
    @InjectRepository(CustomerRepository) private customerRepository: CustomerRepository,
    @InjectRepository(User) private userRepository: Repository<User>
  ) {}

  @Get()
  @UseInterceptors(CacheInterceptor)
  async get(): Promise<any> {
    const user = await this.userRepository.findOne({ where: { id: 1 }, relations: ['customer'] })
    console.log(user.customer.name)
    const customer = await this.customerRepository.findOne({ where: { id: 1 }, select: ['id', 'name'] })
    return { customer: customer.name, email: user.email }
  }
}

I would like using the CacheInterceptor along any modules without import the CacheModule each one.

Nest can't resolve dependencies of the APP_INTERCEPTOR (UUID: 6aa42c77-1bac-4098-b217-1b01eb268240) (?, Reflector). Please make sure that the argument at index [0] is available in the CustomerModule context.

1

1 Answers

3
votes

If you have { provide: APP_INTERCEPTOR, useClass: CacheInterceptor } you don't need to add in the @UseInterceptors() decorator in your controller. You should have the CahceInterceptor working by default with the rest of the set up