@edirect/redis
v11.0.50
Published
Redis client module for eDirect NestJS applications. Wraps the `redis` Node.js client and exposes a `RedisService` with high-level methods for key-value, hash, and set operations — all with automatic JSON serialization and centralized error logging.
Maintainers
Keywords
Readme
@edirect/redis
Redis client module for eDirect NestJS applications. Wraps the redis Node.js client and exposes a RedisService with high-level methods for key-value, hash, and set operations — all with automatic JSON serialization and centralized error logging.
Features
- Global module — register once, inject
RedisServiceanywhere - Automatic JSON serialization/deserialization for stored values
- TTL support with configurable expiry types (
EX,PX,EXAT,PXAT) - Hash operations (
hget,hgetall) - Conditional set (
setnx) for atomic operations - Integrated error logging via
@edirect/logger - Health check via
asyncPing()
Installation
pnpm add @edirect/redis
# or
npm install @edirect/redisUsage
Register in your AppModule
import { Module } from '@nestjs/common';
import { ConfigModule } from '@edirect/config';
import { LoggerModule } from '@edirect/logger';
import { RedisModule } from '@edirect/redis';
@Module({
imports: [
ConfigModule,
LoggerModule.register({ output: 'console' }),
RedisModule,
],
})
export class AppModule {}Because RedisModule is decorated with @Global(), you only need to import it once at the root module.
Inject and use RedisService
import { Injectable } from '@nestjs/common';
import { RedisService } from '@edirect/redis';
@Injectable()
export class CacheService {
constructor(private readonly redis: RedisService) {}
async cachePolicy(policyId: string, data: object): Promise<void> {
// Store with 5-minute TTL
await this.redis.set(`policy:${policyId}`, data, 300);
}
async getPolicy(policyId: string): Promise<object | null> {
return this.redis.get(`policy:${policyId}`) as Promise<object | null>;
}
async isAlive(): Promise<boolean> {
return this.redis.asyncPing();
}
}Environment Variables
| Variable | Description | Required |
| ----------- | ----------------------------------------------------------------------- | -------- |
| REDIS_URL | Redis connection URL (e.g., redis://localhost:6379) | Yes |
| REDIS_TTL | Default TTL in seconds when ttl param is omitted (use 0 for no TTL) | No |
API
RedisService
| Method | Signature | Description |
| ----------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- |
| get | (key: string): Promise<string \| object \| null> | Get and JSON-parse a value by key |
| mget | (keys: string[]): Promise<string[] \| object[]> | Get and JSON-parse multiple keys |
| set | (key: string, data: object \| string, ttl?: number, ttlType?: 'EX' \| 'PX' \| 'EXAT' \| 'PXAT'): Promise<void> | Set a value with optional TTL. Falls back to REDIS_TTL env. |
| del | (key: string): Promise<void> | Delete a key |
| setnx | (key: string, data: object \| string): Promise<boolean> | Set only if the key does not exist. Returns true if set. |
| hget | (hash: string, field: string): Promise<string \| null> | Get a single field from a hash |
| hgetall | (hash: string): Promise<{ [key: string]: string }> | Get all fields from a hash |
| keys | (pattern: string): Promise<string \| string[]> | Find keys matching a pattern |
| asyncPing | (): Promise<boolean> | Returns true if Redis responds to PING |
TTL Types
| ttlType | Description |
| -------------- | ------------------------------ |
| EX (default) | Seconds from now |
| PX | Milliseconds from now |
| EXAT | Unix timestamp in seconds |
| PXAT | Unix timestamp in milliseconds |
Examples
// Store a string with 1-hour TTL
await redis.set('session:abc', 'user-data', 3600);
// Store an object (auto-serialized to JSON)
await redis.set('user:123', { name: 'John', role: 'admin' }, 600);
// Read back (auto-deserialized from JSON)
const user = await redis.get('user:123'); // → { name: 'John', role: 'admin' }
// Atomic set (only if key doesn't exist)
const wasSet = await redis.setnx('lock:job-1', 'worker-1');
// Hash operations
await redis.hget('config:th-broker', 'maxPolicies');
const allConfig = await redis.hgetall('config:th-broker');
// Wildcard key lookup
const sessionKeys = await redis.keys('session:*');