### Install NestJS Valkey Module Source: https://github.com/mekh/nestjs-valkey/blob/main/README.md Install the module using npm. This is the first step to integrating Valkey into your NestJS application. ```bash npm install @toxicoder/nestjs-valkey ``` -------------------------------- ### Acquire and Release Distributed Locks Source: https://github.com/mekh/nestjs-valkey/blob/main/README.md Use ValkeyService to implement distributed locking. This example shows how to acquire a lock, perform an operation, and release the lock, ensuring atomicity. The lock is held for a specified duration (e.g., 30 seconds). ```typescript 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, ): Promise { 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); } } } ``` -------------------------------- ### get(key) Source: https://context7.com/mekh/nestjs-valkey/llms.txt Retrieves the value for a key. Returns null if the key does not exist. ```APIDOC ## get(key) ### Description Retrieves the value for a key. ### Parameters - **key** (string) - The key to retrieve. ### Returns - **Promise** - The value associated with the key, or `null` if the key does not exist. ``` -------------------------------- ### Get Value by Key with Valkey Source: https://context7.com/mekh/nestjs-valkey/llms.txt Use `get` to retrieve the value associated with a key. Returns `null` if the key does not exist. ```typescript import { Injectable } from '@nestjs/common'; import { ValkeyService } from 'nestjs-valkey'; @Injectable() export class UserCacheService { constructor(private readonly valkey: ValkeyService) {} async getUser(userId: string): Promise { const raw = await this.valkey.get(`user:${userId}`); // raw: '{"name":"Alice"}' or null return raw ? JSON.parse(raw) : null; } } ``` -------------------------------- ### ValkeyModule.forRoot(options) Source: https://context7.com/mekh/nestjs-valkey/llms.txt Register the Valkey module synchronously with explicit configuration. Accepts either a `ValkeySingleConfig` (ioredis `RedisOptions`) or a `ValkeyClusterConfig` with `startupNodes` and `clusterOptions`. ```APIDOC ## ValkeyModule.forRoot(options) Registers the module synchronously with explicit configuration. Accepts either a `ValkeySingleConfig` (ioredis `RedisOptions`) or a `ValkeyClusterConfig` with `startupNodes` and `clusterOptions`. ```typescript // Single-node import { Module } from '@nestjs/common'; import { ValkeyModule } from '@toxicoder/nestjs-valkey'; @Module({ imports: [ ValkeyModule.forRoot({ host: 'localhost', port: 6379, password: 'secret', db: 1, keyPrefix: 'prod:', }), ], }) export class AppModule {} // Cluster @Module({ imports: [ ValkeyModule.forRoot({ startupNodes: [ 'redis://node1:6379', 'redis://node2:6379', 'redis://node3:6379', ], clusterOptions: { keyPrefix: 'prod:', redisOptions: { password: 'secret' }, }, }), ], }) export class AppModule {} ``` ``` -------------------------------- ### ValkeyModule.forRootAsync(options) Source: https://context7.com/mekh/nestjs-valkey/llms.txt Register the Valkey module asynchronously, enabling dynamic configuration via `useFactory`, `useClass`, or `useExisting`. Supports the `global` flag to make `ValkeyService` available application-wide without re-importing the module. ```APIDOC ## ValkeyModule.forRootAsync(options) Registers the module asynchronously, enabling dynamic configuration via `useFactory`, `useClass`, or `useExisting`. Supports the `global` flag to make `ValkeyService` available application-wide without re-importing the module. ```typescript // useFactory with ConfigService import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { ValkeyModule } from '@toxicoder/nestjs-valkey'; @Module({ imports: [ ConfigModule.forRoot(), ValkeyModule.forRootAsync({ global: true, // ValkeyService available everywhere imports: [ConfigModule], inject: [ConfigService], useFactory: (config: ConfigService) => ({ host: config.get('VALKEY_HOST', 'localhost'), port: config.get('VALKEY_PORT', 6379), password: config.get('VALKEY_PASSWORD'), keyPrefix: config.get('VALKEY_PREFIX', ''), }), }), ], }) export class AppModule {} // useClass — implement ValkeyConfigFactory import { Injectable } from '@nestjs/common'; import { ValkeyConfigFactory, ValkeyOptions } from '@toxicoder/nestjs-valkey'; @Injectable() export class MyValkeyConfig implements ValkeyConfigFactory { createConfig(): ValkeyOptions { return { host: 'localhost', port: 6379 }; } } @Module({ imports: [ ValkeyModule.forRootAsync({ useClass: MyValkeyConfig }), ], }) export class AppModule {} ``` ``` -------------------------------- ### Configure ValkeyModule with forRoot (Cluster Mode) Source: https://github.com/mekh/nestjs-valkey/blob/main/README.md Configure the ValkeyModule for cluster mode using forRoot. Specify startup nodes and cluster-specific options like key prefix and authentication for the Redis instances. ```typescript 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 {} ``` -------------------------------- ### ValkeyService Methods Source: https://github.com/mekh/nestjs-valkey/blob/main/README.md This section details the available methods on the ValkeyService for interacting with Valkey. ```APIDOC ## ValkeyService Methods - `getClient()`: Returns the underlying Valkey client - `set(key, value)`: Sets a key-value pair - `setEx(key, value, ttlSec)`: Sets a key with EX (seconds) TTL - `setPx(key, value, ttlMs)`: Sets a key with PX (milliseconds) TTL - `setNx(key, value, ttlSec?)`: Sets a key only if it does not exist; optionally with EX TTL. Returns boolean indicating if the key was set - `setPnx(key, value, ttlMs?)`: Sets a key only if it does not exist; optionally with PX TTL. Returns boolean indicating if the key was set - `get(key)`: Gets the value for a key - `del(key | string[])`: Deletes a key or multiple keys - `exists(key | string[])`: Checks if one or more keys exist. Returns the number of existing keys - `expire(key, seconds)`: Sets a key's time to live in seconds - `ping()`: Pings the Valkey server - `disconnect()`: Disconnects from the Valkey server - `acquireLock(key, ttlSec)`: Acquires a distributed lock - `releaseLock(...keys)`: Releases one or more locks ``` -------------------------------- ### Configure ValkeyModule with forRoot (Single Node) Source: https://github.com/mekh/nestjs-valkey/blob/main/README.md Use the forRoot static method to configure the ValkeyModule with direct connection options for a single Valkey node. Provide host, port, and optional authentication or key prefix. ```typescript 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 {} ``` -------------------------------- ### Configure ValkeyModule with Environment Variables Source: https://github.com/mekh/nestjs-valkey/blob/main/README.md Import the ValkeyModule without any options to automatically configure it using environment variables. Ensure the necessary Valkey environment variables are set. ```typescript import { Module } from '@nestjs/common'; import { ValkeyModule } from '@toxicoder/nestjs-valkey'; @Module({ imports: [ValkeyModule], }) export class AppModule {} ``` -------------------------------- ### Register ValkeyModule Synchronously with forRoot() Source: https://context7.com/mekh/nestjs-valkey/llms.txt Register the Valkey module synchronously with explicit configuration options. Accepts either ValkeySingleConfig or ValkeyClusterConfig. ```typescript // Single-node import { Module } from '@nestjs/common'; import { ValkeyModule } from '@toxicoder/nestjs-valkey'; @Module({ imports: [ ValkeyModule.forRoot({ host: 'localhost', port: 6379, password: 'secret', db: 1, keyPrefix: 'prod:', }), ], }) export class AppModule {} // Cluster @Module({ imports: [ ValkeyModule.forRoot({ startupNodes: [ 'redis://node1:6379', 'redis://node2:6379', 'redis://node3:6379', ], clusterOptions: { keyPrefix: 'prod:', redisOptions: { password: 'secret' }, }, }), ], }) export class AppModule {} ``` -------------------------------- ### ping() Source: https://context7.com/mekh/nestjs-valkey/llms.txt Pings the Valkey server to check its availability. Returns 'PONG' on successful connection. ```APIDOC ## ping() ### Description Pings the Valkey server. Returns `'PONG'` on success. Useful for health checks. ### Method `ping()` ### Parameters None ### Request Example ```typescript await this.valkey.ping(); ``` ### Response #### Success Response - **response** (string) - 'PONG' on success. ``` -------------------------------- ### ValkeyModule Registration (Environment Variables) Source: https://context7.com/mekh/nestjs-valkey/llms.txt Register the Valkey module using only environment variables for configuration. This is suitable for twelve-factor app deployments where configuration is injected at runtime. ```APIDOC ## ValkeyModule (environment-variable based, no options) Registers the module using only environment variables (`VALKEY_MODE`, `VALKEY_HOST`, `VALKEY_PORT`, `VALKEY_DB`, `VALKEY_PASSWORD`, `VALKEY_PREFIX`). Suitable for twelve-factor app deployments where config is injected at runtime. ```typescript // app.module.ts import { Module } from '@nestjs/common'; import { ValkeyModule } from '@toxicoder/nestjs-valkey'; @Module({ imports: [ValkeyModule], // reads all config from process.env }) export class AppModule {} // Environment variables (single-node): // VALKEY_MODE=single // VALKEY_HOST=127.0.0.1 // VALKEY_PORT=6379 // VALKEY_DB=0 // VALKEY_PASSWORD=secret // VALKEY_PREFIX=myapp: ``` ``` -------------------------------- ### ValkeyService.getClient() Source: https://context7.com/mekh/nestjs-valkey/llms.txt Returns the underlying raw `iovalkey` client (`ValkeyClient` for single-node or `ValkeyCluster` for cluster). Use this to access any `iovalkey` API not wrapped by `ValkeyService`. ```APIDOC ## ValkeyService Methods ### `getClient()` Returns the underlying raw `iovalkey` client (`ValkeyClient` for single-node or `ValkeyCluster` for cluster). Use this to access any `iovalkey` API not wrapped by `ValkeyService`. ```typescript import { Injectable } from '@nestjs/common'; import { ValkeyService } from '@toxicoder/nestjs-valkey'; @Injectable() export class CacheService { constructor(private readonly valkey: ValkeyService) {} async pipeline() { const client = this.valkey.getClient(); // Use raw iovalkey pipeline for batched commands const results = await client .pipeline() .set('key1', 'value1') .set('key2', 'value2') .get('key1') .exec(); // results: [[null, 'OK'], [null, 'OK'], [null, 'value1']] return results; } } ``` ``` -------------------------------- ### setPx(key, value, ttlMs) Source: https://context7.com/mekh/nestjs-valkey/llms.txt Sets a key with a time-to-live in milliseconds. This corresponds to the Redis `SET key value PX ttl` command. ```APIDOC ## setPx(key, value, ttlMs) ### Description Sets a key with a time-to-live in milliseconds. ### Parameters - **key** (string) - The key to set. - **value** (any) - The value to associate with the key. - **ttlMs** (number) - The time-to-live in milliseconds. ### Returns - **Promise** - Resolves with 'OK' upon successful setting. ``` -------------------------------- ### Set Key if Not Exists (NX) Source: https://context7.com/mekh/nestjs-valkey/llms.txt Use `setNx` to set a key only if it does not exist (NX option). It returns `true` if the key was written and `false` if it already existed. An optional TTL in seconds can be provided. ```typescript import { Injectable } from '@nestjs/common'; import { ValkeyService } from 'nestjs-valkey'; @Injectable() export class IdempotencyService { constructor(private readonly valkey: ValkeyService) {} async registerRequest(requestId: string): Promise { // Without TTL — key persists const isNew = await this.valkey.setNx(`req:${requestId}`, '1'); // isNew: true → first time seen // isNew: false → duplicate request // With TTL — auto-expire after 60s const isNewWithTtl = await this.valkey.setNx(`req:${requestId}`, '1', 60); return isNewWithTtl; } } ``` -------------------------------- ### setEx(key, value, ttlSec) Source: https://context7.com/mekh/nestjs-valkey/llms.txt Sets a key with a time-to-live in seconds. This corresponds to the Redis `SET key value EX ttl` command. ```APIDOC ## setEx(key, value, ttlSec) ### Description Sets a key with a time-to-live in seconds. ### Parameters - **key** (string) - The key to set. - **value** (any) - The value to associate with the key. - **ttlSec** (number) - The time-to-live in seconds. ### Returns - **Promise** - Resolves with 'OK' upon successful setting. ``` -------------------------------- ### setPnx(key, value, ttlMs?) Source: https://context7.com/mekh/nestjs-valkey/llms.txt Sets a key only if it does not exist, with an optional TTL in milliseconds. Returns true if written. ```APIDOC ## setPnx(key, value, ttlMs?) ### Description Sets a key only if it does not exist, with an optional TTL in milliseconds. ### Parameters - **key** (string) - The key to set. - **value** (any) - The value to associate with the key. - **ttlMs** (number, optional) - The time-to-live in milliseconds. ### Returns - **Promise** - `true` if the key was written, `false` if it already existed. ``` -------------------------------- ### Set Key with Expiration (Seconds) Source: https://context7.com/mekh/nestjs-valkey/llms.txt Use `setEx` to set a key with a time-to-live in seconds, similar to Redis `SET key value EX ttl`. ```typescript import { Injectable } from '@nestjs/common'; import { ValkeyService } from 'nestjs-valkey'; @Injectable() export class SessionService { constructor(private readonly valkey: ValkeyService) {} async createSession(sessionId: string, userId: string): Promise { // Expires in 30 minutes const result = await this.valkey.setEx(`session:${sessionId}`, userId, 1800); // result: 'OK' return result; } } ``` -------------------------------- ### Set Key with Expiration (Milliseconds) Source: https://context7.com/mekh/nestjs-valkey/llms.txt Use `setPx` to set a key with a time-to-live in milliseconds, equivalent to Redis `SET key value PX ttl`. ```typescript import { Injectable } from '@nestjs/common'; import { ValkeyService } from 'nestjs-valkey'; @Injectable() export class RateLimitService { constructor(private readonly valkey: ValkeyService) {} async setRateWindow(clientIp: string, count: string): Promise { // Expires in 1500ms const result = await this.valkey.setPx(`rate:${clientIp}`, count, 1500); // result: 'OK' return result; } } ``` -------------------------------- ### Register ValkeyModule Asynchronously with forRootAsync() Source: https://context7.com/mekh/nestjs-valkey/llms.txt Register the Valkey module asynchronously, allowing dynamic configuration via useFactory, useClass, or useExisting. Supports the global flag to make ValkeyService available application-wide. ```typescript // useFactory with ConfigService import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { ValkeyModule } from '@toxicoder/nestjs-valkey'; @Module({ imports: [ ConfigModule.forRoot(), ValkeyModule.forRootAsync({ global: true, // ValkeyService available everywhere imports: [ConfigModule], inject: [ConfigService], useFactory: (config: ConfigService) => ({ host: config.get('VALKEY_HOST', 'localhost'), port: config.get('VALKEY_PORT', 6379), password: config.get('VALKEY_PASSWORD'), keyPrefix: config.get('VALKEY_PREFIX', ''), }), }), ], }) export class AppModule {} // useClass — implement ValkeyConfigFactory import { Injectable } from '@nestjs/common'; import { ValkeyConfigFactory, ValkeyOptions } from '@toxicoder/nestjs-valkey'; @Injectable() export class MyValkeyConfig implements ValkeyConfigFactory { createConfig(): ValkeyOptions { return { host: 'localhost', port: 6379 }; } } @Module({ imports: [ ValkeyModule.forRootAsync({ useClass: MyValkeyConfig }), ], }) export class AppModule {} ``` -------------------------------- ### Set Key if Not Exists (PNX) with Milliseconds TTL Source: https://context7.com/mekh/nestjs-valkey/llms.txt Use `setPnx` to set a key only if it does not exist, with an optional TTL in milliseconds. Returns `true` if the key was written. ```typescript import { Injectable } from '@nestjs/common'; import { ValkeyService } from 'nestjs-valkey'; @Injectable() export class ThrottleService { constructor(private readonly valkey: ValkeyService) {} async throttle(action: string): Promise { // Allow action once every 500ms const allowed = await this.valkey.setPnx(`throttle:${action}`, '1', 500); // allowed: true → proceed // allowed: false → throttled return allowed; } } ``` -------------------------------- ### exists(key | string[]) Source: https://context7.com/mekh/nestjs-valkey/llms.txt Checks if one or more keys exist. Returns the count of existing keys. ```APIDOC ## exists(key | string[]) ### Description Checks if one or more keys exist. ### Parameters - **key** (string | string[]) - The key or an array of keys to check. ### Returns - **Promise** - The count of existing keys among the provided list. ``` -------------------------------- ### Register ValkeyModule with Environment Variables Source: https://context7.com/mekh/nestjs-valkey/llms.txt Register the Valkey module using only environment variables for configuration. This is suitable for twelve-factor app deployments where configuration is injected at runtime. ```typescript import { Module } from '@nestjs/common'; import { ValkeyModule } from '@toxicoder/nestjs-valkey'; @Module({ imports: [ValkeyModule], // reads all config from process.env }) export class AppModule {} // Environment variables (single-node): // VALKEY_MODE=single // VALKEY_HOST=127.0.0.1 // VALKEY_PORT=6379 // VALKEY_DB=0 // VALKEY_PASSWORD=secret // VALKEY_PREFIX=myapp: ``` -------------------------------- ### Configure ValkeyModule with forRootAsync Source: https://github.com/mekh/nestjs-valkey/blob/main/README.md Use forRootAsync for dynamic configuration of the ValkeyModule, allowing configuration values to be injected from other modules like ConfigModule. This is useful for managing configuration externally. ```typescript 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 {} ``` -------------------------------- ### setNx(key, value, ttlSec?) Source: https://context7.com/mekh/nestjs-valkey/llms.txt Sets a key only if it does not exist (NX). Optionally accepts a TTL in seconds. Returns true if the key was written, false if it already existed. ```APIDOC ## setNx(key, value, ttlSec?) ### Description Sets a key only if it does not exist (NX). Optionally accepts a TTL in seconds. ### Parameters - **key** (string) - The key to set. - **value** (any) - The value to associate with the key. - **ttlSec** (number, optional) - The time-to-live in seconds. ### Returns - **Promise** - `true` if the key was written, `false` if it already existed. ``` -------------------------------- ### Valkey Health Check with ping() Source: https://context7.com/mekh/nestjs-valkey/llms.txt Implements a health check for Valkey server connectivity using the `ping()` method. Useful for application health monitoring. ```typescript import { Injectable } from '@nestjs/common'; import { HealthIndicator, HealthIndicatorResult } from '@nestjs/terminus'; import { ValkeyService } from '@toxicoder/nestjs-valkey'; @Injectable() export class ValkeyHealthIndicator extends HealthIndicator { constructor(private readonly valkey: ValkeyService) { super(); } async isHealthy(key: string): Promise { try { const response = await this.valkey.ping(); // response: 'PONG' return this.getStatus(key, response === 'PONG'); } catch { return this.getStatus(key, false); } } } ``` -------------------------------- ### Access Raw iovalkey Client via ValkeyService Source: https://context7.com/mekh/nestjs-valkey/llms.txt Retrieve the underlying raw iovalkey client from ValkeyService to utilize any iovalkey API not directly exposed by ValkeyService. This is useful for advanced operations like batched commands using pipelines. ```typescript import { Injectable } from '@nestjs/common'; import { ValkeyService } from '@toxicoder/nestjs-valkey'; @Injectable() export class CacheService { constructor(private readonly valkey: ValkeyService) {} async pipeline() { const client = this.valkey.getClient(); // Use raw iovalkey pipeline for batched commands const results = await client .pipeline() .set('key1', 'value1') .set('key2', 'value2') .get('key1') .exec(); // results: [[null, 'OK'], [null, 'OK'], [null, 'value1']] return results; } } ``` -------------------------------- ### disconnect() Source: https://context7.com/mekh/nestjs-valkey/llms.txt Gracefully disconnects from the Valkey server. This method should be called during application shutdown. ```APIDOC ## disconnect() ### Description Gracefully disconnects from the Valkey server. Should be called during application teardown via `OnModuleDestroy`. ### Method `disconnect()` ### Parameters None ### Request Example ```typescript this.valkey.disconnect(); ``` ### Response None. This method performs an action and does not return a value. ``` -------------------------------- ### expire(key, seconds) Source: https://context7.com/mekh/nestjs-valkey/llms.txt Sets or updates the expiration of an existing key in seconds. Returns 1 if successful, 0 if the key does not exist. ```APIDOC ## expire(key, seconds) ### Description Sets or updates the expiration of an existing key in seconds. ### Parameters - **key** (string) - The key whose expiration needs to be set or updated. - **seconds** (number) - The expiration time in seconds. ### Returns - **Promise** - `1` if the expiration was set successfully, `0` if the key does not exist. ``` -------------------------------- ### set(key, value) Source: https://context7.com/mekh/nestjs-valkey/llms.txt Sets a key-value pair with no expiration. This method is directly bound from the underlying iovalkey client. ```APIDOC ## set(key, value) ### Description Sets a key-value pair with no expiration. ### Parameters - **key** (string) - The key to set. - **value** (any) - The value to associate with the key. ### Returns - **Promise** - Resolves with 'OK' upon successful setting. ``` -------------------------------- ### acquireLock(key, ttlSec) Source: https://context7.com/mekh/nestjs-valkey/llms.txt Attempts to acquire a distributed lock. Returns true if the lock is acquired, false otherwise. ```APIDOC ## acquireLock(key, ttlSec) ### Description Attempts to acquire a distributed lock by setting a key with an NX + EX guard. Returns `true` if the lock was acquired, `false` if another process holds it. ### Method `acquireLock(key: string, ttlSec: number)` ### Parameters #### Path Parameters - **key** (string) - Required - The unique identifier for the lock. - **ttlSec** (number) - Required - The time-to-live for the lock in seconds. ### Request Example ```typescript const acquired = await this.valkey.acquireLock(lockKey, 30); ``` ### Response #### Success Response - **acquired** (boolean) - `true` if the lock was acquired, `false` otherwise. ``` -------------------------------- ### Check Existence of One or More Keys Source: https://context7.com/mekh/nestjs-valkey/llms.txt Use `exists` to check if one or more keys exist. It returns the count of keys that are present in the database. ```typescript import { Injectable } from '@nestjs/common'; import { ValkeyService } from 'nestjs-valkey'; @Injectable() export class CacheService { constructor(private readonly valkey: ValkeyService) {} async isCached(keys: string[]): Promise { const count = await this.valkey.exists(keys); // count: number of keys found among the provided list return count === keys.length; // true only if ALL keys exist } } ``` -------------------------------- ### Set Key-Value Pair with Valkey Source: https://context7.com/mekh/nestjs-valkey/llms.txt Use `set` to store a key-value pair without any expiration. The value is directly bound from the underlying iovalkey client. ```typescript import { Injectable } from '@nestjs/common'; import { ValkeyService } from 'nestjs-valkey'; @Injectable() export class UserCacheService { constructor(private readonly valkey: ValkeyService) {} async cacheUser(userId: string, data: object): Promise { const result = await this.valkey.set(`user:${userId}`, JSON.stringify(data)); // result: 'OK' return result; } } ``` -------------------------------- ### Graceful Valkey Disconnect on Module Destroy Source: https://context7.com/mekh/nestjs-valkey/llms.txt Ensures graceful disconnection from the Valkey server when the NestJS application is shutting down. Implement `OnModuleDestroy` to call `disconnect()`. ```typescript import { Injectable, OnModuleDestroy } from '@nestjs/common'; import { ValkeyService } from '@toxicoder/nestjs-valkey'; @Injectable() export class AppService implements OnModuleDestroy { constructor(private readonly valkey: ValkeyService) {} onModuleDestroy(): void { this.valkey.disconnect(); // Logs: 'Valkey - Disconnected from Valkey server' } } ``` -------------------------------- ### Update Expiration of an Existing Key Source: https://context7.com/mekh/nestjs-valkey/llms.txt Use `expire` to set or update the expiration time of an existing key in seconds. It returns `1` if successful and `0` if the key does not exist. ```typescript import { Injectable } from '@nestjs/common'; import { ValkeyService } from 'nestjs-valkey'; @Injectable() export class SessionService { constructor(private readonly valkey: ValkeyService) {} async renewSession(sessionId: string): Promise { // Extend session by another 30 minutes on activity const result = await this.valkey.expire(`session:${sessionId}`, 1800); // result: 1 → TTL updated; 0 → session key not found return result === 1; } } ``` -------------------------------- ### del(key | string[]) Source: https://context7.com/mekh/nestjs-valkey/llms.txt Deletes one or more keys. Returns the number of keys that were actually removed. ```APIDOC ## del(key | string[]) ### Description Deletes one or more keys. ### Parameters - **key** (string | string[]) - The key or an array of keys to delete. ### Returns - **Promise** - The number of keys that were actually removed. ``` -------------------------------- ### Disconnect ValkeyService on Module Destroy Source: https://github.com/mekh/nestjs-valkey/blob/main/README.md Implement the `OnModuleDestroy` interface to ensure the ValkeyService disconnects gracefully when the NestJS application shuts down. This prevents resource leaks. ```typescript 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(); } } ``` -------------------------------- ### Acquire and Release Distributed Lock Source: https://context7.com/mekh/nestjs-valkey/llms.txt Attempts to acquire a distributed lock with a specified Time-To-Live (TTL) using `acquireLock`. Ensures the lock is released using `releaseLock` in a `finally` block to prevent deadlocks. ```typescript import { Injectable } from '@nestjs/common'; import { ValkeyService } from '@toxicoder/nestjs-valkey'; @Injectable() export class PaymentService { constructor(private readonly valkey: ValkeyService) {} async processPayment(orderId: string): Promise { const lockKey = `lock:order:${orderId}`; const acquired = await this.valkey.acquireLock(lockKey, 30); // 30-second TTL if (!acquired) { throw new Error(`Order ${orderId} is already being processed`); } try { // Critical section — safe from concurrent execution await this.chargeCustomer(orderId); } finally { await this.valkey.releaseLock(lockKey); } } private async chargeCustomer(orderId: string): Promise { /* ... */ } } ``` -------------------------------- ### releaseLock(...keys) Source: https://context7.com/mekh/nestjs-valkey/llms.txt Releases one or more distributed locks by deleting their keys. Accepts a variadic list of lock key names. ```APIDOC ## releaseLock(...keys) ### Description Releases one or more distributed locks by deleting their keys. Accepts a variadic list of lock key names. ### Method `releaseLock(...keys: string[])` ### Parameters #### Path Parameters - **keys** (string[]) - Required - A list of lock key names to release. ### Request Example ```typescript await this.valkey.releaseLock(lockKey1, lockKey2); ``` ### Response None. This method performs an action and does not return a value. ``` -------------------------------- ### Inject ValkeyService in NestJS Source: https://github.com/mekh/nestjs-valkey/blob/main/README.md Inject the ValkeyService into your NestJS services or controllers to interact with Valkey. Ensure ValkeyModule is imported in your AppModule. ```typescript 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 { // Plain set return this.valkeyService.set(key, value); } async setWithTtlSeconds(key: string, value: string): Promise { // SET with EX (seconds) return this.valkeyService.setEx(key, value, 30); } async setWithTtlMs(key: string, value: string): Promise { // SET with PX (milliseconds) return this.valkeyService.setPx(key, value, 1500); } async setIfNotExists(key: string, value: string): Promise { // NX without TTL (returns true if key was set) return this.valkeyService.setNx(key, value); } async setIfNotExistsWithTtl(key: string, value: string): Promise { // NX with EX (seconds) return this.valkeyService.setNx(key, value, 60); } async getValue(key: string): Promise { return this.valkeyService.get(key); } } ``` -------------------------------- ### Delete One or More Keys Source: https://context7.com/mekh/nestjs-valkey/llms.txt Use `del` to remove one or more keys. The method returns the count of keys that were successfully removed. ```typescript import { Injectable } from '@nestjs/common'; import { ValkeyService } from 'nestjs-valkey'; @Injectable() export class CacheEvictionService { constructor(private readonly valkey: ValkeyService) {} async evict(userId: string): Promise { // Delete multiple related keys at once const count = await this.valkey.del([ `user:${userId}`, `user:${userId}:profile`, `user:${userId}:permissions`, ]); // count: number of keys deleted (0–3) return count; } } ``` -------------------------------- ### Release Multiple Distributed Locks Source: https://context7.com/mekh/nestjs-valkey/llms.txt Releases one or more distributed locks by deleting their keys using `releaseLock`. Accepts a variadic list of lock key names, useful for releasing multiple acquired locks. ```typescript import { Injectable } from '@nestjs/common'; import { ValkeyService } from '@toxicoder/nestjs-valkey'; @Injectable() export class InventoryService { constructor(private readonly valkey: ValkeyService) {} async reserveItems(itemIds: string[]): Promise { const lockKeys = itemIds.map(id => `lock:item:${id}`); // Acquire all locks const results = await Promise.all( lockKeys.map(key => this.valkey.acquireLock(key, 10)), ); if (results.some(acquired => !acquired)) { // Release any locks that were acquired before failing await this.valkey.releaseLock(...lockKeys.filter((_, i) => results[i])); throw new Error('Could not acquire all item locks'); } try { await this.updateInventory(itemIds); } finally { // Release all locks at once await this.valkey.releaseLock(...lockKeys); } } private async updateInventory(itemIds: string[]): Promise { /* ... */ } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.