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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@tresdoce-nestjs-toolkit/redis

v2.0.13

Published

Tresdoce NestJS Toolkit - Módulo de Redis para cache

Readme

Este módulo está pensado para ser utilizado en NestJS Starter, o cualquier proyecto que utilice una configuración centralizada, siguiendo la misma arquitectura del starter.

Glosario


📝 Requerimientos básicos

🛠️ Instalar dependencia

npm install -S @tresdoce-nestjs-toolkit/redis
yarn add @tresdoce-nestjs-toolkit/redis

📦 Dependencias internas

Este paquete no tiene dependencias internas del toolkit. Puede utilizarse de forma independiente.

⚙️ Configuración

Agregar los datos de conexión a Redis en configuration.ts utilizando el key redis con los datos de conexión desde las variables de entorno.

//./src/config/configuration.ts
import { Typings } from '@tresdoce-nestjs-toolkit/core';
import { registerAs } from '@nestjs/config';

export default registerAs('config', (): Typings.AppConfig => {
  return {
    //...
    redis: {
      name: encodeURIComponent(process.env.REDIS_NAME),
      host: encodeURIComponent(process.env.REDIS_HOST),
      port: parseInt(process.env.REDIS_PORT, 10) || 6379,
      username: encodeURIComponent(process.env.REDIS_USERNAME),
      password: encodeURIComponent(process.env.REDIS_PASSWORD),
    },
    //...
  };
});

URL de conexión

El módulo construye automáticamente la URL de conexión a partir de los parámetros de configuración usando el formato:

redis[s]://[[username][:password]@][host][:port][/db-number]

Por ejemplo, con protocol: 'redis', host: 'localhost' y port: 6379 sin credenciales, la URL resultante será redis://localhost:6379.

name: Nombre lógico de la conexión Redis. Se usa como identificador interno del cliente.

  • Type: String
  • Required: false
  • Default: UUID generado automáticamente

protocol: Protocolo de conexión.

  • Type: String
  • Required: false
  • Default: redis
  • Values: redis | rediss

host: Servidor para conectarse a Redis.

  • Type: String
  • Required: true
  • Values: localhost | 127.0.0.1 | <host>

port: Puerto para conectarse a Redis.

  • Type: Number
  • Required: true
  • Default: 6379

username: Nombre de usuario para conectarse a Redis.

  • Type: String
  • Required: false
  • Default: default

password: Contraseña de usuario para conectarse a Redis.

  • Type: String
  • Required: false

database: Base de datos de Redis (número de DB).

  • Type: number
  • Required: false
  • Default: 0

Para más información sobre los parámetros de conexión, consultar el Client Configuration de Redis.

👨‍💻 Uso

Importación del módulo (configuración centralizada)

Importar el RedisModule en el archivo app.module.ts. El módulo es @Global() y obtiene la configuración automáticamente desde ConfigService (key config.redis).

//./src/app.module.ts
import { RedisModule } from '@tresdoce-nestjs-toolkit/redis';

@Module({
  //...
  imports: [
    //...
    RedisModule,
    //...
  ],
  //...
})
export class AppModule {}

Importación estática con register

Para proyectos que no usan la configuración centralizada, se puede registrar el módulo con opciones directas:

//./src/app.module.ts
import { RedisModule } from '@tresdoce-nestjs-toolkit/redis';

@Module({
  imports: [
    RedisModule.register({
      host: 'localhost',
      port: 6379,
      password: 'mypassword',
    }),
  ],
})
export class AppModule {}

Uso con RedisService

Inyectar el RedisService en el servicio para interactuar con Redis mediante los métodos de alto nivel:

import { Injectable } from '@nestjs/common';
import { RedisService } from '@tresdoce-nestjs-toolkit/redis';

@Injectable()
export class CatService {
  constructor(private readonly redisService: RedisService) {}

  async redisEcho() {
    return await this.redisService.echo('Hello world!');
  }
}

Uso con el cliente REDIS_CLIENT

Si necesitas acceso a todos los comandos de Redis, inyecta directamente el cliente nativo usando el token REDIS_CLIENT:

import { Inject, Injectable } from '@nestjs/common';
import { REDIS_CLIENT } from '@tresdoce-nestjs-toolkit/redis';
import { RedisClientType } from 'redis';

@Injectable()
export class CacheService {
  constructor(@Inject(REDIS_CLIENT) private readonly redisClient: RedisClientType) {}

  async customCommand() {
    // Acceso a todos los comandos de Redis
    return await this.redisClient.hSet('myHash', 'field', 'value');
  }
}

Comandos disponibles en RedisService

Si bien Redis tiene una gran cantidad de comandos, el RedisService expone los más utilizados. Para acceder a todos los comandos, inyectar el REDIS_CLIENT directamente.

Echo

Retorna la cadena de texto enviada.

await this.redisService.echo('Hello world!');

Exists

Retorna un Boolean indicando si la key existe en Redis.

await this.redisService.exists('myKey');

Set

Guarda un value asociado a una key. El parámetro seconds es opcional e indica el tiempo de expiración.

await this.redisService.set('myKey', 'my value');
await this.redisService.set('myKey', { key: 'value' });
await this.redisService.set('myKey', 'my value', 10); // expira en 10 segundos

Get

Retorna el valor de la key. Devuelve null si la key no existe.

await this.redisService.get('myKey');

Del

Elimina la key y su valor de Redis. Retorna boolean.

await this.redisService.del('myKey');

Copy

Copia el valor de una key con un nuevo nombre.

await this.redisService.copy('myKey', 'myKeyCopy');

Rename

Renombra una key existente.

await this.redisService.rename('myKeyCopy', 'myKey2');

FlushAll

Elimina todos los datos almacenados en Redis.

await this.redisService.flushAll();

📖 API Reference

RedisModule

Módulo global (@Global()). Exporta REDIS_CLIENT y RedisService.

| Método | Descripción | | --------------------------------------------- | ------------------------------------------------------------------ | | RedisModule (sin argumentos) | Carga la configuración desde ConfigService (key config.redis). | | RedisModule.register(options: RedisOptions) | Inicialización estática con opciones directas. |

RedisService

| Método | Firma | Descripción | | ----------- | ------------------------------------------------------------- | ------------------------------------------- | | clientRef | get clientRef(): RedisClientType | Getter que expone el cliente Redis nativo | | echo | (msg: string) => Promise<string> | Retorna la cadena enviada | | exists | (key: string) => Promise<boolean> | Verifica si una key existe | | set | (key: string, value: any, seconds?: number) => Promise<any> | Guarda un valor (serializado a JSON) | | get | (key: string) => Promise<any> | Obtiene un valor (deserializado desde JSON) | | del | (key: string) => Promise<boolean> | Elimina una key | | copy | (source: string, destination: string) => Promise<boolean> | Copia una key con nuevo nombre | | rename | (key: string, newKey: string) => Promise<string> | Renombra una key | | flushAll | () => Promise<string> | Borra toda la base de datos Redis |

RedisOptions

Extiende RedisClientOptions de la librería redis.

| Campo | Tipo | Requerido | Default | Descripción | | ---------- | -------- | --------- | ----------- | ------------------------------ | | host | string | Sí | — | Servidor Redis | | port | number | Sí | 6379 | Puerto Redis | | protocol | string | No | 'redis' | Protocolo (redis o rediss) | | username | string | No | 'default' | Usuario Redis | | password | string | No | — | Contraseña Redis | | database | number | No | 0 | Número de base de datos | | name | string | No | UUID | Nombre lógico de la conexión |

Constantes exportadas

| Constante | Descripción | | ---------------------------------- | --------------------------------------------------------------- | | REDIS_CLIENT | Token de inyección del cliente Redis nativo (RedisClientType) | | REDIS_MODULE_OPTIONS | Token de inyección de las opciones del módulo | | REDIS_MSG_IS_READY | Mensaje de log cuando Redis está listo | | REDIS_MSG_SUCCESSFULLY_CONNECTED | Mensaje de log cuando la conexión es exitosa | | REDIS_MSG_ERROR_CONNECTED | Mensaje de log cuando ocurre un error de conexión |

Re-exportaciones

Este paquete re-exporta completamente la librería redis (export * from 'redis'), por lo que todos los tipos, interfaces y funciones de redis (como RedisClientType, createClient, etc.) pueden importarse directamente desde @tresdoce-nestjs-toolkit/redis.

📄 Changelog

Todos los cambios notables de este paquete se documentarán en el archivo Changelog.