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

nestjs-caching-module

v1.2.0

Published

A configurable caching module for NestJS supporting in-memory and Redis stores

Readme

NestJS Caching Module

Un módulo de caché configurable para NestJS que soporta almacenamiento en memoria (usando LRU Cache) y Redis (usando ioredis), con soporte opcional de logging para monitoreo y debugging.

Instalación

npm install nestjs-caching-module

Configuración

Configuración Básica

import { CachingModule } from 'nestjs-caching-module';

@Module({
  imports: [
    CachingModule.forRoot({
      store: 'memory', // o 'redis'
    }),
  ],
})
export class AppModule {}

Configuración con Redis

import { CachingModule } from 'nestjs-caching-module';

@Module({
  imports: [
    CachingModule.forRoot({
      store: 'redis',
      standaloneOptions: {
        host: 'localhost',
        port: 6379,
        // otras opciones de ioredis
      },
      // Opcionalmente, clusterNodes si usas Redis Cluster
      // clusterNodes: [{ host: 'localhost', port: 7000 }],
    }),
  ],
})
export class AppModule {}

Configuración con Memoria (LRU Cache)

import { CachingModule } from 'nestjs-caching-module';

@Module({
  imports: [
    CachingModule.forRoot({
      store: 'memory',
      memoryOptions: {
        max: 1000, // número máximo de items
        ttl: 1000 * 60 * 5, // tiempo de vida en milisegundos
      },
    }),
  ],
})
export class AppModule {}

Uso

Inyectar el Servicio de Caché

import { CacheModuleService } from 'nestjs-caching-module';

@Injectable()
export class YourService {
  constructor(private readonly cacheService: CacheModuleService) {}

  async getData(key: string) {
    // Obtener datos del caché
    const cachedData = await this.cacheService.get(key);
    if (cachedData) {
      return cachedData;
    }

    // Si no está en caché, obtener de la fuente original
    const data = await this.getDataFromSource();
    
    // Guardar en caché
    await this.cacheService.set(key, data, 300); // TTL de 300 segundos
    
    return data;
  }
}

Usar el Repositorio con Caché

import { CachedRepository } from 'nestjs-caching-module';
import { CacheModuleService } from 'nestjs-caching-module';

@Injectable()
export class YourService {
  private cachedRepo: CachedRepository<YourEntity>;

  constructor(
    private readonly repo: YourRepository,
    private readonly cacheService: CacheModuleService,
  ) {
    this.cachedRepo = new CachedRepository(
      this.repo,
      this.cacheService,
      300, // TTL en segundos
      'your-prefix:', // prefijo para las keys
    );
  }

  async findById(id: string) {
    return this.cachedRepo.findById(id);
  }

  async save(entity: YourEntity) {
    return this.cachedRepo.save(entity);
  }

  async delete(id: string) {
    return this.cachedRepo.delete(id);
  }
}

API

CacheModuleService

  • get<T>(key: string): Promise<T | undefined>
  • set<T>(key: string, value: T, ttlSeconds?: number): Promise<void>
  • del(key: string): Promise<void>

CachedRepository

  • findById(id: K): Promise<T | null>
  • save(entity: T & { id: K }): Promise<T>
  • delete(id: K): Promise<void>

Opciones de Configuración

Redis Options

Todas las opciones de ioredis son soportadas.

También puedes definir un arreglo clusterNodes si deseas usar Redis en modo cluster.

Memory Options

Opciones de lru-cache:

  • max: número máximo de items
  • ttl: tiempo de vida en milisegundos
  • maxSize: tamaño máximo en bytes
  • allowStale: permitir items expirados
  • updateAgeOnGet: actualizar edad al obtener
  • updateAgeOnHas: actualizar edad al verificar existencia

Logging (Opcional)

Para habilitar logs automáticos en consola de cada operación de get, set y del:

  1. Establece la variable de entorno CACHE_LOGS=true
  2. Asegúrate de que tu entorno de NestJS tenga habilitado el nivel de log debug

Ejemplo:

CACHE_LOGS=true npm run start:dev

Los logs utilizan el Logger de NestJS e incluyen:

  • GET key: cuando se intenta obtener un valor
  • SET key: al guardar un valor
  • DEL key: al eliminar una key
  • Eventos de conexión, errores y reconexión en Redis

Contribuir

Las contribuciones son bienvenidas. Por favor, abre un issue o un pull request para sugerir cambios o mejoras.