Core features:
- Based on official ioredis client for NodeJS;
- Includes standalone and cluster clients;
- Covered with unit and e2e tests;
- Basic module without unnecessary boilerplate.
To install the package, run:
npm install @quazex/nestjs-ioredis ioredis
To use the ioredis module in your NestJS application, import it into your root module (e.g., AppModule
).
import { Module } from '@nestjs/common';
import { RedisClientModule } from '@quazex/nestjs-ioredis';
@Module({
imports: [
RedisClientModule.forRoot({
url: 'redis://localhost:6379/1',
}),
],
})
export class AppModule {}
Once the module is registered, you can inject instance of the Redis
or Cluster
into your providers:
import { Injectable } from '@nestjs/common';
import { InjectRedisClient } from '@quazex/nestjs-ioredis/client';
import { Redis } from 'ioredis';
@Injectable()
export class StorageService {
constructor(@InjectRedisClient() private readonly client: Redis) {}
async write(key: string, value: object) {
await this.client.set(key, value);
}
async read(key: string) {
return this.client.get(key);
}
}
If you need dynamic configuration, use forRootAsync
:
@Module({
imports: [
RedisClientModule.forRootAsync({
useFactory: async (config: SomeConfigProvider) => ({
url: config.REDIS_URL,
}),
inject: [
SomeConfigProvider,
],
}),
],
})
export class AppModule {}
You need to enable shutdown hooks to activate connection management when the application is shut down. You can read more about lifecycle hooks on the NestJS documentation page.
// main.ts
const app = await NestFactory.create(AppModule);
// Starts listening for shutdown hooks
app.enableShutdownHooks(); // <<<
await app.listen(process.env.PORT ?? 3000);
MIT