Home > OS >  How to pass a @liaoliaots/nestjs-redis redis connection to global guard constructor
How to pass a @liaoliaots/nestjs-redis redis connection to global guard constructor

Time:12-13

i'm new in NestJS and have some misunderstands with @liaoliaots/nestjs-redis(https://github.com/liaoliaots/nestjs-redis) package. For example, i have a guard with following constructor:

import { InjectRedis } from '@liaoliaots/nestjs-redis';
import { Redis } from 'ioredis';

@Injectable()
export class SomeGuard implements CanActivate {
    constructor(@InjectRedis() redis: Redis) {}
    
    ...
}

and then i want that guard to be global:

//main.ts
...
app.useGlobalGuards(new SomeGuard(/* what??? */));
...

so thats a problem: what i need to pass? @InjectRedis makes weird things:)

thx for responding

CodePudding user response:

Instead of app.useGlobalGuards, use this another way:

// ...
import { Module } from '@nestjs/common'
import { APP_GUARD } from '@nestjs/core'

@Module({
  // ...
  providers: [
    {
      provide: APP_GUARD,
      useClass: SomeGuard,
    },
  ],
})
export class AppModule {}

is cleaner and helps you avoid polluting your boostrap funcion. Also, it lets Nest resolves that Redis dependency. Otherwise you'll need to get this dependency and pass it to new SomeGuard using
const redis = app.get(getRedisToken())

  • Related