@toxicoder/nestjs-valkey
v0.0.2
Published
Valkey module for NestJS
Readme
NestJS Valkey Module
A NestJS module for integrating with Valkey, a Redis-compatible database.
Table of Contents
Installation
npm install @toxicoder/nestjs-valkeyDescription
The NestJS Valkey module provides a simple way to integrate Valkey (a Redis-compatible database) with your NestJS application. This module uses the iovalkey package to connect to Valkey servers and provides a service with methods for common operations.
Key Features
- Support for both single-node and cluster configurations
- Easy integration with NestJS dependency injection
- Configuration through environment variables or programmatically
- Methods for common Redis operations (get, set, del, etc.)
- Distributed lock mechanism
Environment Variables
| Variable | Type | Default | Description | | --------------- | ------------ | ----------- | -------------------------------------------------------------------------------------- | | VALKEY_MODE | string | 'single' | Connection mode: 'single' or 'cluster' | | VALKEY_HOST | string/array | '127.0.0.1' | For single mode: host address. For cluster mode: comma-separated list of startup nodes | | VALKEY_PORT | number | 6379 | Port number (single mode only) | | VALKEY_DB | number | undefined | Database number (single mode only) | | VALKEY_PASSWORD | string | undefined | Password for authentication | | VALKEY_PREFIX | string | '' | Prefix for all keys |
Configuration
Using environment variables (no code configuration)
If you prefer configuring via environment variables only, simply import the module without options. The module will read configuration from process.env using the variables listed in the Environment Variables section.
import { Module } from '@nestjs/common';
import { ValkeyModule } from '@toxicoder/nestjs-valkey';
@Module({
imports: [ValkeyModule],
})
export class AppModule {}forRoot
Use forRoot to configure the module with direct options:
import { Module } from '@nestjs/common';
import { ValkeyModule } from '@toxicoder/nestjs-valkey';
@Module({
imports: [
ValkeyModule.forRoot({
host: 'localhost',
port: 6379,
password: 'password',
keyPrefix: 'app:',
}),
],
})
export class AppModule {}For cluster configuration:
import { Module } from '@nestjs/common';
import { ValkeyModule } from '@toxicoder/nestjs-valkey';
@Module({
imports: [
ValkeyModule.forRoot({
startupNodes: ['redis://localhost:6379', 'redis://localhost:6380'],
clusterOptions: {
keyPrefix: 'app:',
redisOptions: {
password: 'password',
},
},
}),
],
})
export class AppModule {}forRootAsync
Use forRootAsync for dynamic configuration:
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { ValkeyModule } from '@toxicoder/nestjs-valkey';
@Module({
imports: [
ConfigModule.forRoot(),
ValkeyModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
host: configService.get('VALKEY_HOST'),
port: configService.get('VALKEY_PORT'),
password: configService.get('VALKEY_PASSWORD'),
keyPrefix: configService.get('VALKEY_PREFIX'),
}),
}),
],
})
export class AppModule {}Usage
Basic Usage
Inject the ValkeyService into your service or controller:
import { Injectable } from '@nestjs/common';
import { ValkeyService } from '@toxicoder/nestjs-valkey';
@Injectable()
export class AppService {
constructor(private readonly valkeyService: ValkeyService) {}
async setValue(key: string, value: string): Promise<string> {
// Plain set
return this.valkeyService.set(key, value);
}
async setWithTtlSeconds(key: string, value: string): Promise<string> {
// SET with EX (seconds)
return this.valkeyService.setEx(key, value, 30);
}
async setWithTtlMs(key: string, value: string): Promise<string> {
// SET with PX (milliseconds)
return this.valkeyService.setPx(key, value, 1500);
}
async setIfNotExists(key: string, value: string): Promise<boolean> {
// NX without TTL (returns true if key was set)
return this.valkeyService.setNx(key, value);
}
async setIfNotExistsWithTtl(key: string, value: string): Promise<boolean> {
// NX with EX (seconds)
return this.valkeyService.setNx(key, value, 60);
}
async getValue(key: string): Promise<string | null> {
return this.valkeyService.get(key);
}
}Acquiring and Releasing Locks
The module provides methods for distributed locks:
import { Injectable } from '@nestjs/common';
import { ValkeyService } from '@toxicoder/nestjs-valkey';
@Injectable()
export class LockService {
constructor(private readonly valkeyService: ValkeyService) {}
async performWithLock(
key: string,
operation: () => Promise<void>,
): Promise<void> {
const lockAcquired = await this.valkeyService.acquireLock(key, 30); // Lock for 30 seconds
if (!lockAcquired) {
throw new Error('Could not acquire lock');
}
try {
await operation();
} finally {
await this.valkeyService.releaseLock(key);
}
}
}Cleanup
Implement the OnModuleDestroy interface to properly disconnect from Valkey when your application shuts down:
import { Injectable, OnModuleDestroy } from '@nestjs/common';
import { ValkeyService } from '@toxicoder/nestjs-valkey';
@Injectable()
export class AppService implements OnModuleDestroy {
constructor(private readonly valkeyService: ValkeyService) {}
onModuleDestroy() {
this.valkeyService.disconnect();
}
}API Reference
ValkeyService Methods
getClient(): Returns the underlying Valkey clientset(key, value): Sets a key-value pairsetEx(key, value, ttlSec): Sets a key with EX (seconds) TTLsetPx(key, value, ttlMs): Sets a key with PX (milliseconds) TTLsetNx(key, value, ttlSec?): Sets a key only if it does not exist; optionally with EX TTL. Returns boolean indicating if the key was setsetPnx(key, value, ttlMs?): Sets a key only if it does not exist; optionally with PX TTL. Returns boolean indicating if the key was setget(key): Gets the value for a keydel(key | string[]): Deletes a key or multiple keysexists(key | string[]): Checks if one or more keys exist. Returns the number of existing keysexpire(key, seconds): Sets a key's time to live in secondsping(): Pings the Valkey serverdisconnect(): Disconnects from the Valkey serveracquireLock(key, ttlSec): Acquires a distributed lockreleaseLock(...keys): Releases one or more locks
License
ISC
