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 🙏

© 2024 – Pkg Stats / Ryan Hefner

data-cache-manager

v1.1.1

Published

cache with redis management

Downloads

722

Readme

data-cache-manager

data-cache-manager is a complete caching solution for NestJS applications, designed for performance optimization by handling caching with Redis transparently. This package includes built-in configuration options, automatic cache invalidation, and TTL (time-to-live) settings, making it easy to integrate into your projects without additional dependencies.

Features

Centralized Cache Management: All caching functionality is managed within the package, no additional packages required. Customizable TTL: Define cache duration via environment variables. Route-Based Cache Keys: Each request URL acts as a cache key, with optional prefix-based cache invalidation for flexibility. Automatic Cache Invalidation: Upon resource creation, update, or deletion, related cache entries are automatically removed.

Installation

To install this package, simply add it to your project:

npm install data-cache-manager

Configuration

1. Global Cache Configuration

In the main application module, configure CacheManagerModule to set up caching across your application.

Example app.module.ts Configuration


import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { DataCacheModule, DataCacheInterceptor } from 'data-cache-manager';

@Module({
  imports: [
    DataCacheModule.forRoot({
      status: process.env.REDIS_STATUS || true,
      host: process.env.REDIS_HOST || 'localhost',
      port: parseInt(process.env.REDIS_PORT, 10) || 6379,
      ttl: parseInt(process.env.CACHE_TTL, 10) || 600,
      cacheKeyPrefix: process.env.CACHE_PREFIX || '',
    }),
  ],
 controllers: [AppController],
  providers: [
    AppService,
    {
      provide: APP_INTERCEPTOR,
      useClass: DataCacheInterceptor,
    },
  ],
})
export class AppModule {}

2. Local Cache Configuration

In the concerned ressource module, configure CacheManagerModule to set up caching accross your application.

Example services.module.ts configuration

import { Module } from '@nestjs/common';
import { ServicesService } from './services.service';
import { ServicesController } from './services.controller';
import { DataCacheInterceptor, DataCacheModule } from 'data-cache-manager';
import { APP_INTERCEPTOR } from '@nestjs/core';

@Module({
  controllers: [ServicesController],
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: DataCacheInterceptor,
    },
    ServicesService
  ],
  imports:[
    DataCacheModule.forRoot({
      status: Boolean(process.env.REDIS_STATUS) || true,
      host: process.env.REDIS_HOST || 'localhost',
      port: parseInt(process.env.REDIS_PORT, 10) || 6379,
      ttl: parseInt(process.env.CACHE_TTL, 10) || 600,
      cacheKeyPrefix: process.env.CACHE_PREFIX || '/api/def-fiscalite/services',
    }),
  ],
})
export class ServicesModule {}

Environment Variables

The package manages Redis configuration based on environment variables. Variable Description Default: REDIS_STATUS Redis global configuration status REDIS_HOST Redis server host localhost REDIS_PORT Redis server port 6379 CACHE_TTL Default Time-To-Live for cache 600 (10 min) CACHE_PREFIX Prefix for cache keys api

Example of .env file with the values:

REDIS_STATUS=true
REDIS_HOST=localhost
REDIS_PORT=6379
CACHE_TTL=600
CACHE_PREFIX=

3. There is a possibility to manage the cache manually in the service of the concerned ressource after configurating CacheManagerModule in the module of that concerned ressource with parameter status in false and not configuring DataCacheInterceptor.

Example of manually management in the services.service.ts

import { HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common';
import { CreateServiceDto } from './dto/create-service.dto';
import { UpdateServiceDto } from './dto/update-service.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Service } from './entities/service.entity';
import { Repository } from 'typeorm';
import { DataCacheService } from 'data-cache-manager';

@Injectable()
export class ServicesService {

  constructor(
    @InjectRepository(Service)
    readonly serviceRepository: Repository<Service>,
    private readonly dataServices: DataCacheService,
    ){}
    
  async create(createServiceDto: CreateServiceDto, cacheKey: string) {
    let service = await this.serviceRepository.findOneBy({name: createServiceDto.name});
    if(service)
      return service;
    service = await this.serviceRepository.save(createServiceDto);
    if(service){
      await this.dataServices.clearCacheByPrefix(cacheKey);
      return service;
    }
    throw new HttpException(`l'enregistrement de ce service a échoué!`,HttpStatus.CONFLICT);
  }

  async findAll(cacheKey: string) {
  
    // Verify if the cache key already exists, by getting its data
    let services = await this.dataServices.getCache(cacheKey);
    if (!services) {
      // if that cache key does not exist in the cache, we add it by getting the data from database;
      services = await this.serviceRepository.find();
      await this.dataServices.setCache(cacheKey, services, 600);
    }
    return services;
  }
}

That is for the well management of the cache keys; In that the case the cache will passed manually. Service's controller example:

import { Controller, Get, Post, Body, Request } from '@nestjs/common';
import { ServicesService } from './services.service';
import { CreateServiceDto } from './dto/create-service.dto';

@Controller('services')
export class ServicesController {
  constructor(private readonly servicesService: ServicesService) {}

  @Post()
  create(@Body() createServiceDto: CreateServiceDto, @Request() req) {
    return this.servicesService.create(createServiceDto, req.url);
  }

  @Get()
  findAll(@Request() req) {
    return this.servicesService.findAll(req.url);
  }
}

Usage

  1. Automatic Caching on Routes

This package automatically applies caching to routes based on the URL. For example, the following route will cache its response under a key derived from the URL. Controller Example

import { Controller, Get } from '@nestjs/common';

@Controller('products')
export class ProductsController {
  @Get()
  async findAll() {
    // Your logic here; data will be cached automatically
    return [{ id: 1, name: 'Product 1' }, { id: 2, name: 'Product 2' }];
  }
}

How It Works

Cache Management: The package sets a cache key for each URL and caches the response automatically.
TTL Settings: Cache expiration is determined by the CACHE_TTL environment variable, which you can set per environment.
Invalidation Logic: Use the clearCacheByPrefix(prefix: string) method to clear cached entries with keys that start with the specified prefix.

License

This project is licensed under the MIT License.