Tayber
Tayber

Reputation: 43

In NestJs, I added Redis as cache manager, when I specify {ttl : 0} it throws a type error, it was working before

I am using Redis as the cache manager in NestJs project. I was using a code like:

await this.productCacheManager.set('products/time', data, { ttl: 60} )

When I delete the ttl argument or just put 60 there, it doesn't work and it immediately removes the record from redis, so I was using { ttl: 60} which was working until now. I do not know what happend but now it throws an error like:

Argument of type '{ ttl: number; }' is not assignable to parameter of type 'number'.

The parameter I am typing is a number...

Trying to make it work again like before.

Upvotes: 3

Views: 9331

Answers (4)

Muhammad Ali Usman
Muhammad Ali Usman

Reputation: 69

maybe this answer is too late. But if anyone experiences the same problem, you can try this method. i use these dependencies:

"cache-manager": "^5.2.3", "cache-manager-redis-store": "^3.0.1",

await this.cacheManager.set(
  key,
  value,
  {ttl: 1000} as any
);

Upvotes: 5

Arlen Vasconcelos
Arlen Vasconcelos

Reputation: 39

With cache-manager v5, you can use { ttl: time_in_seconds }, for example:

await this.cacheManager.set(key, value, { ttl: 60 }); // ttl 60 seconds

If you are working with typescript you can use CacheStore interface from cache-manager.

import { CacheStore } from '@nestjs/cache-manager';

Upvotes: 3

Olivier H
Olivier H

Reputation: 898

If you use cache-manager v4 and cache-manager-redis-store v2, you need to pass an options object, as in

cache.set(key, value, { ttl: 60 }) // in seconds

(And that's because the redis store v2 code expects an object)

If you are using cache-manager v5, though, you may pass an integer, although I've not yet been able to make cache-manager-redis-store@^3 work well with cache-manager@^5.

cache.set(key, value, 60000) // in milliseconds with v5!

⚠️ As of today (2023-02-24), NestJS recommends using cache-manager v4.

Source: NestJS documentation as for the seconds/milliseconds consideration.

The object vs number specification, I found out myself by trying different combinations and parsing the redis store code.

Upvotes: 5

Huthaifa Muayyad
Huthaifa Muayyad

Reputation: 12373

You only need to pass the number, not the object { ttl: 60}, just use 60, because here it is only reserved for til and it knows it's going to be a number.

Upvotes: -1

Related Questions