The nestjs cache module based on cache-manager & decorators 🍃

Overview

Nest Logo

A progressive Node.js framework for building efficient and scalable server-side applications.

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

It should be used on any endpoint you want to cache (if it is not used globally on controller)

@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/nestjs-cache-module';
You might also like...

API Back-End de NodeJS com NestJS

A progressive Node.js framework for building efficient and scalable server-side applications. Description Nest framework TypeScript starter repository

May 29, 2022

Nestjs + Typescript + GraphQL

Nestjs Boilerplate: Nestjs + Typescript + GraphQL How to run Install dependencies yarn install Start server for development yarn start:dev Start ser

Jun 27, 2022

ObjectionJS on steroids for your nestjs application!

Introduction Almost every application nowadays, requires a database to persist data. We have integrated ObjectionJS as our supported ORM. ObjectionJS

Dec 15, 2022

This is a boilerplate for Nodejs (Nestjs/typescript) that can be used to make http server application.

Hexagonal architecture Table of Contents Overview Code architecture source code Service build information Regular user Advanced user Deployment Helm K

Sep 13, 2022

🦁 REST API for the NestJS + Next.js Todo application

Create new NestJS project $ npm i -g @nestjs/cli $ npm i -g yarn $ nest new api-lesson # set strict true in tsconfig.json Install packages # install

Jan 4, 2023

Bluzelle is a smart, in-memory data store. It can be used as a cache or as a database.

SwarmDB ABOUT SWARMDB Bluzelle brings together the sharing economy and token economy. Bluzelle enables people to rent out their computer storage space

Dec 31, 2022

NodeJS PostgreSQL database performance insights. Locks, index usage, buffer cache hit ratios, vacuum stats and more.

Node Postgres Extras NodeJS port of Heroku PG Extras with several additions and improvements. The goal of this project is to provide powerful insights

Nov 14, 2022

A lightweight way to cache on graphQL servers

A lightweight way to cache on graphQL servers

cacheflowQL What is cacheflowQL? CacheflowQL is an npm package with complex caching algorithms that provide developers deep insights into their GraphQ

Nov 16, 2022

A remote nodejs Cached sqlite Database Server, for you to have your perfect MAP Cache Saved and useable remotely.

A remote nodejs Cached sqlite Database Server, for you to have your perfect MAP Cache Saved and useable remotely.

A remote nodejs Cached sqlite Database Server, for you to have your perfect MAP Cache Saved and useable remotely. Easy Server and Client Creations, fast, stores the Cache before stopping and restores it again! it uses ENMAP

Dec 18, 2022
external eventbus module for @nestjs/cqrs

A Cqrs External EventBus module for Nest framework (node.js) Now available: Redis-EventBus Installation with npm npm install --save nest-external-even

H.John Choi 9 Dec 23, 2022
This is a repository that contains an simple NestJS API about Movies developed at Blue EdTech.

NestJS Movies Technologies and requirements NestJS JavaScript TypeScript Prisma MySQL Project This is a repository that contains an simple NestJS API

Isabella Nunes 2 Sep 28, 2021
Starter template for NestJS 😻 includes GraphQL with Prisma Client, Passport-JWT authentication, Swagger Api and Docker

Instructions Starter template for ?? NestJS and Prisma. Checkout NestJS Prisma Schematics to automatically add Prisma support to your Nest application

notiz.dev 1.6k Jan 4, 2023
around nestjs, with prisma and some graphql lib,write less code,create power api

介绍 这是一个 prisma + nestjs + graphql 的集成示例 对于开发者来说,特别是使用 graphql 的时候,只需要写非常少量的代码即可完成数据的各种操作,同时也支持接口透传。 开发&部署 本地开发 npm run start:dev swagger 地址:http://loc

芋头 26 Nov 24, 2022
Nestjs boilerplate for beginners.

Description Nest framework boilerplate. Installation $ npm install Running the docker for postgres or simply update env with running postgres values $

Harris Gurung 18 Nov 30, 2022
API developed using NestJS, TypeORM, PgMem and concepts of Clean Architecture

The Powerful NestJS A progressive Node.js framework for building efficient and scalable server-side applications. Clean Architecture The project has b

Matheus Alexandre 20 Jan 2, 2023
Simple CRUD application with Nestjs, Prisma and Docker with Postgres

A progressive Node.js framework for building efficient and scalable server-side applications. Description Nest framework TypeScript starter repository

Torr7s 5 Nov 6, 2022
First NestJS project powered by TypeScript (Simple CRUD)

First Nest TS (TypeScript) First NestJS project powered by TypeScript (Simple CRUD) Routes Get All GET http://localhost:3000/products/ Get one GET htt

Max Base 3 Feb 22, 2022
NestJS + MikroORM example repository for testing within transactional contexts. Achieve a much faster test suite.

Description Nest NestJS + MikroORM example repository for testing within transactional contexts. Running tests in transactions will speedup your test

Tolga Paksoy 5 Dec 20, 2022
An in-depth implementation of Clean Architecture using NestJS and type-script

Clean Architecture With NestJS Description It's been a while since my last article on how to implement clean architecture on Node.js applications, git

null 297 Dec 28, 2022