epicweb-dev / cachified

🤑 wrap virtually everything that can store by key to act as cache with ttl/max-age, stale-while-validate, parallel fetch protection and type-safety support
MIT License
916 stars 26 forks source link

redisCacheAdapter does not cache if ttl is set because of the #17

Closed TapaiBalazs closed 1 year ago

TapaiBalazs commented 1 year ago

I have tried out this library for caching API requests with Redis (v4+), using the redisCacheAdapter for adapter. I followed the documentation on how to set up caching, but every request made through the getFreshValue method I passed in it.

After some debugging, I found that the cachified call suppresses an error when setting a value into redis, so I tried manually calling the adapter's set method:

await cachifiedCache.set('key', { value: 1, metadata: { ttl: 60000, createdTime: new Date().getTime() } })

That revealed the error, which was the following: ERR value is not an integer or out of range. Which was strange, since the ttl value I passed should not be problematic, so I checked out the adapter's source code and found how the expiration is set:

{
  EXAT: (ttl + createdTime) / 1000
}

Based on the above, I think redis needs an unix timestamp passed to the EXAT param, that is why the / 1000 is there, but if we come from a javascript time, that won't be an integer:

const time = new Date().getTime() // something like: 1670395771645

console.log((300_000 + time) / 1000) // will log 1670396071.645

I copied the redisCacheAdapter into my code and updated the setter to:

{
  EXAT: Math.round((ttl + createdTime) / 1000),
}

And now it works for me. :)

github-actions[bot] commented 1 year ago

:tada: This issue has been resolved in version 3.0.1 :tada:

The release is available on:

Your semantic-release bot :package::rocket: