Nest auth Redis
nestjs module to ease connection with a single Redis instance.
It creates a ioredis.Redis
instance and make it injectable using Nestjs DI
Installation
$ npm install --save @nest-auth/redis ioredis
$ npm install --save-dev @types/ioredis
Or
$ yarn add @nest-auth/redis ioredis
$ yarn add -D @types/ioredis
Import it in a module
import { Module } from '@nestjs/common';
import { RedisModule } from '@nest-auth/redis';
@Module({
imports: [
//...
RedisModule.forRoot({
ioredis: { // ioRedis options
host: 'localhost',
port: 6379,
username: 'redisUser',
password: 'supersecret',
//...
},
// Optionally, you can pass a redis connection uri
url: 'redis://redisUser:supersecret@localhost:6379',
}),
// Or with Async configuration
RedisModule.forRootAsync({
import: [ConfigModule],
inject: [ConfigService],
useFactory: config => config.get('redis'),
}),
//...
],
})
export class AppModule {}
Usage
get the redis connection using the @InjectRedis()
decorator
import { Injectable } from '@nestjs/common';
import { InjectRedis } from '@nest-auth/redis';
import ioredis from 'ioredis';
@Injectable()
export class SomeService {
constructor(
@InjectRedis()
private readonly redis: ioredis.Redis,
) {}
}
If you need to get the Redis connection outside the Nest scope (say in main.ts
to use it in some Adapter only middleware), get it using getRedisToken()
:
import { getRedisToken } from '@nest-auth/redis';
//...
const app = await NestFactory.create(AppModule);
const redis = app.get(getRedisToken());
//...