data-cache-manager
v1.1.1
Published
cache with redis management
Downloads
51
Maintainers
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
- 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.