skip to Main Content

I have registered redis as cache manager in nestjs which is taking default value from env of 0 i.e no limit which is needed for some keys. But I want to pass custom ttl to another key using set(key, value, ttl) which is still taking ttl from env not from set function.

  • node: v18.14.2
  • cache-manager: 5.1.6
  • cache-manager-redis-store: 3.0.1

redis module

@Module({
  imports: [
    CacheModule.registerAsync({
      imports: [],
      useFactory: async (
        config: ConfigType<typeof configuration>,
      ): RedisClientOptions => ({
        store: redisStore,
        socket: {
          host: config.redis.host,
          port: config.redis.port,
          tls: config.redis.tls,
        },
        ttl: parseInt(config.redis.ttl, 10),
      }),
      inject: [configuration.KEY],
    }),
  ],
  providers: [RedisService],
  exports: [RedisService],
})
export class RedisModule {}

redis service

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

@Injectable()
export class RedisService {
  constructor(@Inject(CACHE_MANAGER) private cache: Cache) {}

  async setWithTtl(
    key: string | number,
    value: any,
  ): Promise<void> {
    try {
      await this.cache.set(
        JSON.stringify(key),
        JSON.stringify(value),
        500,
      );
      return;
    } catch (err) {
      throw err;
    }
  }

2

Answers


  1. Chosen as BEST ANSWER

    After some research I found the answer. Update the set function to

    await this.cache.set(
        JSON.stringify(key),
        JSON.stringify(value),
        { ttl: 500 } as any,
      );
    

    Here 500 must be in seconds not in milliseconds even if cache-manager is v5

    More details about the issue can be found here


  2. I’m not sure but maybe you are facing this situation?

    WARNING
    cache-manager version 4 uses seconds for TTL (Time-To-Live). The current version of cache-manager (v5) has switched to using milliseconds instead. NestJS doesn’t convert the value, and simply forwards the ttl you provide to the library. In other words:
    If using cache-manager v4, provide ttl in seconds
    If using cache-manager v5, provide ttl in milliseconds
    Documentation is referring to seconds, since NestJS was released targeting version 4 of cache-manager.

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