0.0.3 • Published 3 years ago

@zirus/nestjs-cache-module v0.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

zirus-cache

zirus-cache for Nest.JS - simple and modern cache library

Simple example

@CacheMethod()
@Get()
async getData(): Promise<string[]> {
  return data;
}

Installation

npm install cache-manager
npm install -D @types/cache-manager
npm install @zirus/nestjs-cache-module

Basic usage

Import ZirusModule

@Module({
  imports: [
    ZirusModule.forRoot(),

    // Async registration
    ZirusModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => (({
        store: configService.get('STORE')
      })),
      inject: [ConfigService]
    }),
  ],
})
export class AppModule {}

Customize caching

@Module({
  imports: [
    ZirusModule.forRoot({
        store: 'memory', 
        ttl: 0, //time to live 
        max: 100 // max items in cache
    })
  ],
})
export class AppModule {}

Also you can use different storage like Redis:

npm install cache-manager-redis-store
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import * as redisStore from 'cache-manager-redis-store';

@Module({
  imports: [
    ZirusModule.forRoot({
      store: redisStore,
      max: 100,

      socket: {
        host: 'localhost',
        port: 6379
      }
  })
  ],
  controllers: [AppController]
})
export class AppModule {}

More storages: https://www.npmjs.com/package/cache-manager

Decorators

@CacheMethod()

This decorator can use for controller or endpoint alone

@CacheMethod()
@Controller()
export class DataController {
  @Get()
  async getData(): Promise<string[]> {
    return data;
  }

All GET methods of controller wil be cached

For one endpoint:

@Controller()
export class DataController {
  @CacheMethod()
  @Get()
  async getData(): Promise<string[]> {
    return data;
  }

@SetCacheKey()

This decorator sets a specific cache key for endpoint

By default, the key is generated from the URL (including query parameters)

  @SetCacheKey('key')
  @Get()
  async getData(): Promise<string[]> {
    return data;
  }

@SetCacheTTL()

This decorator sets a specific TTL for endpoint

By default is 0

  @SetCacheTTL(10)
  @Get()
  async getData(): Promise<string[]> {
    return data;
  }

Also you can:

  @SetCacheTTL((context: ExecutionContext) => {
  const headers = context.switchToHttp().getRequest().headers;

  if (headers.flag !== undefined) {
    return 5;
  }

  return 0;
})

@TrackBy()

Sometimes you might want to set up tracking based on different factors, for example, using HTTP headers (e.g. Authorization to properly identify profile endpoints).

@TrackBy work like @SetCacheKey() but he allows get Execution Context and write own function

  @TrackBy((context: ExecutionContext) => {
    return context.switchToHttp().getRequest().headers.authorization
  })
  @Get()
  async getData(): Promise<string[]> {
    return data;
  }

@SetCond()

This decorator determines will be endpoint cached or not

  @SetCond((context) => {
    return context.switchToHttp().getRequest().headers.authorization !== undefined
  })
  @Get()
  async getData(): Promise<string[]> {
    return data;
  }

@Exclude()

This decorator can be used when you don't need to cache one or more endpoints

Example:

@CacheMethod()
@Controller()
export class AppController {

  @Get('/foo')
  async foo(): Promise<string[]> {
    return data;
  }

  @Exclude()
  @Get('/bar')
  async bar(): Promise<string[]> {
    return data;
  }

}

/bar endpoint will not be cached

@Exclude() decorator is literally short entry for

    @SetCond(() => {
    return false;
  })

Own logics

if you need work with cache-manager, you can:

constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
Note:
import {CACHE_MANAGER} from '@zirus-cache';