skip to Main Content

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?

3

Answers


  1. Chosen as BEST ANSWER

    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


  2. If you’re connection a external Redis, I recommend to use ‘async-redis’ package.

    The code will be:

    import * as redis from 'async-redis';
    import redisConfig from '../../config/redis';
    

    On redisConfig:

    export default {
       host: 'your Host',
       port: parseInt('Your Port Conection'),
       // Put the first value in hours
       // Time to expire a data on redis
       expire: 1 * 60 * 60,
       auth_pass: 'password',
    };
    

    So, you run:

    var dbConnection = redis.createClient(config.db.port, config.db.host, 
    {no_ready_check: true}); 
    

    Now you can, execute commands like set and get for your Redis Database.

    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search