skip to Main Content

I’m having trouble when trying to use cache-manager by NestJS,
the problem is the value always return true,

const isSet = await this.cacheManager.store.getClient().set(key, value, 'EX', ttl, 'NX')
console.log("isSet => " + isSet)

if(isSet === true) {
  try {
      //do smth
  } catch(err) {
     console.log("err => " + err)
     throw err;
  } finally {
    //await this.cacheManager.del(key);
  }
}

my question is, when using redis-cli, when i repeatedly do

set key val ex ttl nx

if not exists, it returns OK, but when exists it returns nil.

enter image description here

Why does cache-manager keep returning true?

Depedency Version

"cache-manager": "^3.6.0",
"cache-manager-redis-store": "^2.0.0",

2

Answers


  1. you can try it:

    const isSet = await this.cacheManager.store.getClient().set(key, value, 'EX', ttl, 'NX');
    const actualValue = await this.cacheManager.store.getClient().get(key);
    
    if(actualValue === value) {
      try {
        //do smth
      } catch(err) {
        console.log("err => " + err);
        throw err;
      } finally {
        //await this.cacheManager.del(key);
      }
    }
    
    Login or Signup to reply.
  2. The issue you’re facing might be due to the fact that the set method in cache-manager-redis-store doesn’t return a value. In JavaScript, if a function doesn’t explicitly return a value, it returns undefined. Now, when you use the await keyword with such a function, you’re essentially converting undefined to a promise that resolves with undefined.

    In JavaScript, when you use undefined in a boolean context (like an if statement), it’s coerced to false. But, in your case, you’re explicitly comparing isSet to true (i.e., isSet === true). This comparison will only be true if isSet is indeed true, which it never will be. Therefore, your if condition is never satisfied.

    Instead, you might want to use set and get methods separately and check the result of get method for your key. Here’s a way to do it:

    await this.cacheManager.store.getClient().set(key, value, 'EX', ttl, 'NX');
    
    // Get the value
    const result = await this.cacheManager.store.getClient().get(key);
    
    if (result) {
      try {
        // do something
      } catch(err) {
        console.log("err => " + err);
        throw err;
      } finally {
        //await this.cacheManager.del(key);
      }
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search