Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store a value in redis store using Nestjs

Tags:

redis

nestjs

I have a simple nestjs application, where I have set up a CacheModule using Redis store as follows:

import * as redisStore from 'cache-manager-redis-store';

CacheModule.register({
      store: redisStore,
      host: 'redis',
      port: 6379,
    }),

I would like to use it to store a single value, however, I do not want to do it the built-in way by attaching an interceptor to a controller method, but instead I want to control it manually and be able to set and retrieve the value in the code.

How would I go about doing that and would I even use cache manager for that?

like image 695
Jacobdo Avatar asked May 31 '20 18:05

Jacobdo


People also ask

What is Redis Cache Manager?

CacheManager backed by a Redis cache. This cache manager creates caches by default upon first write. Empty caches are not visible on Redis due to how Redis represents empty data structures. Caches requiring a different RedisCacheConfiguration than the default configuration can be specified via RedisCacheManager.


2 Answers

You can use the official way from Nest.js:

1. Create your RedisCacheModule:

1.1. redisCache.module.ts:

import { Module, CacheModule } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import * as redisStore from 'cache-manager-redis-store';
import { RedisCacheService } from './redisCache.service';

@Module({
  imports: [
    CacheModule.registerAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        store: redisStore,
        host: configService.get('REDIS_HOST'),
        port: configService.get('REDIS_PORT'),
        ttl: configService.get('CACHE_TTL'),
      }),
    }),
  ],
  providers: [RedisCacheService],
  exports: [RedisCacheService] // This is IMPORTANT,  you need to export RedisCacheService here so that other modules can use it
})
export class RedisCacheModule {}

1.2. redisCache.service.ts:

import { Injectable, Inject, CACHE_MANAGER } from '@nestjs/common';
import { Cache } from 'cache-manager';

@Injectable()
export class RedisCacheService {
  constructor(
    @Inject(CACHE_MANAGER) private readonly cache: Cache,
  ) {}

  async get(key) {
    await this.cache.get(key);
  }

  async set(key, value) {
    await this.cache.set(key, value);
  }
}

2. Inject RedisCacheModule wherever you need it:

Let's just assume we will use it in module DailyReportModule:

2.1. dailyReport.module.ts:

import { Module } from '@nestjs/common';
import { RedisCacheModule } from '../cache/redisCache.module';
import { DailyReportService } from './dailyReport.service';

@Module({
  imports: [RedisCacheModule],
  providers: [DailyReportService],
})
export class DailyReportModule {}

2.2. dailyReport.service.ts

We will use the redisCacheService here:

import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { RedisCacheService } from '../cache/redisCache.service';

@Injectable()
export class DailyReportService {
  private readonly logger = new Logger(DailyReportService.name);

  constructor(
    private readonly redisCacheService: RedisCacheService, // REMEMBER TO INJECT THIS
  ) {}

  @Cron('0 1 0 * * *') // Run cron job at 00:01:00 everyday
  async handleCacheDailyReport() {
    this.logger.debug('Handle cache to Redis');
  }
}

You can check my sample code here.

like image 185
Hoang Trinh Avatar answered Sep 20 '22 22:09

Hoang Trinh


Building on Ahmad's comment above, I used the following to enable redis in my nestjs application:

  1. Install and setup nestjs-redis https://www.npmjs.com/package/nestjs-redis per docs.

  2. See the docs here on how to write and read values in a Redis store: https://github.com/NodeRedis/node-redis

like image 45
Jacobdo Avatar answered Sep 20 '22 22:09

Jacobdo