npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@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-valkey

Description

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 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

License

ISC