Home > Software engineering >  Want to use Nestjs with other Redis command
Want to use Nestjs with other Redis command

Time:05-02

I try to implement nestjs backend and redis as caching. I can do it according to the official document https://docs.nestjs.com/techniques/caching#in-memory-cache.

I use the package cache-manager-redis-store and the code in app.module.ts is as shown below.

import { Module, CacheModule } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import * as redisStore from 'cache-manager-redis-store';
import * as Joi from 'joi';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [
    CacheModule.registerAsync({
      imports: [
        ConfigModule.forRoot({
          validationSchema: Joi.object({
            REDIS_HOST: Joi.string().default('localhost'),
            REDIS_PORT: Joi.number().default(6379),
            REDIS_PASSWORD: Joi.string(),
          }),
        }),
      ],
      useFactory: async (configService: ConfigService) => ({
        store: redisStore,
        auth_pass: configService.get('REDIS_PASSWORD'),
        host: configService.get('REDIS_HOST'),
        port: configService.get('REDIS_PORT'),
        ttl: 0,
      }),
      inject: [ConfigService],
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

With this setting, I can use get and set as expected but I want to use other redis command such as hget and zadd. Unfortunately, I cannot find the guide anywhere.

I think there must be a way since cache-manager-redis-store package said that it just passing the configuration to the underlying node_redis package. And node-redis package can use those fancy redis commands.

Would be appreciated if you have solutions.

CodePudding user response:

You can retrieve the underlying redis client by calling
cacheManager.store.getClient() even tho the interface Cache (from cache-manager) doesn't has that getClient method defined. I don't know what's the best way to type that.

The return of that will be the Redis client created by cache-manager-redis-store

CodePudding user response:

I suggest nestjs-redis package. It's compatible with typescript and is dependent on ioredis package thus you get all other Redis APIs as well.

  • Related