Skip to content

Redis

@voltage/redis wraps the redis client for NestJS. It registers a connected client as a global provider and handles connect and quit automatically with the application lifecycle.

Terminal window
yarn add @voltage/redis @voltage/zod zod

Pass configuration directly:

import { RedisModule } from '@voltage/redis';
@Module({
imports: [
RedisModule.register({
url: 'redis://localhost:6379',
}),
],
})
export class AppModule {}

Use a factory when configuration comes from another provider:

import { RedisModule } from '@voltage/redis';
RedisModule.registerAsync({
inject: [AppConfiguration],
useFactory: (config: AppConfiguration) => ({
url: config.redis.url,
password: config.redis.password,
}),
}),

The module is global — you do not need to import it in feature modules.

Inject the client with @InjectRedis():

import { InjectRedis } from '@voltage/redis';
import { RedisClientType } from 'redis';
@Injectable()
export class CacheService {
constructor(@InjectRedis() private readonly redis: RedisClientType) {}
async set(key: string, value: string) {
await this.redis.set(key, value);
}
}

Pass name as the second argument to register additional clients. When omitted, the name defaults to 'default'.

RedisModule.register({ url: 'redis://localhost:6379' }),
RedisModule.register({ url: 'redis://localhost:6380' }, 'cache'),

Use @InjectRedis(name) to select a specific instance:

@Injectable()
export class SomeService {
constructor(
@InjectRedis() private readonly redis: RedisClientType,
@InjectRedis('cache') private readonly cache: RedisClientType,
) {}
}

getClientToken(name?) returns the injection token as a string — useful when wiring up custom providers.

interface RedisConfiguration {
/** `redis[s]://[[username][:password]@][host][:port][/db-number]` */
url?: string;
/** Socket connection options — use when you need explicit host/port or TLS */
socket?: {
host?: string;
port?: number;
path?: string;
tls?: boolean;
connectTimeout?: number;
noDelay?: boolean;
keepAlive?: number | false;
reconnectStrategy?: false | number;
};
/** ACL username */
username?: string;
/** ACL password or the legacy `--requirepass` password */
password?: string;
/** Client name, sent via `CLIENT SETNAME` */
name?: string;
/** Redis database index */
database?: number;
/** Maximum number of queued commands */
commandsQueueMaxLength?: number;
/** Reject commands while reconnecting instead of queuing them */
disableOfflineQueue?: boolean;
/** Connect in `READONLY` mode */
readonly?: boolean;
/** Interval in ms at which a `PING` is sent to keep the connection alive */
pingInterval?: number;
/** Disable sending the client identifier to the server */
disableClientInfo?: boolean;
/** Tag appended to the library name sent to the server */
clientInfoTag?: string;
}