How to use Redis and/or memory cache with node-cache-manager
Upgrading legacy libraries of a (server-side, running on Node) legacy JavaScript application, I had to upgrade (and replace) following libraries:
As there is missing documentation (node-cache-manager-redis-yet
does not have any at all) and there is no current example using a memory cache and Redis at the same time, I spend some time finding the solution. So it might be a useful shortcut for you, if you need to do the same task.
TL;DR
The code I eventually came up with (in short, for more details read further):
The problems and my solutions
cache-manager
's API changed. It changed for better, so this is a good thing, just a bit of work and restructuring of code, as it relies onPromise
s now and the application I am working on is already relying on a workingcache
object on startup.
So I created a wrapper object taking care of theawait
s.
- While the memory cache accepts
null
andundefined
as result values of a wrapped function,cache-manager-redis-yet
does not, and instead of omitting it, it throws an error. If you don't want this error to pop up in your application, you have to catch it (see line 24). cache-manager-redis
is not maintained any more, so I removed it completely.cache-manager-redis-store
is not "officially" supported bycache-manager
, so I used the recommend one:node-cache-manager-redis-yet
, which unfortunately has absolutely no documentation and no example.
It is a fork ofcache-manager-redis-store
, so we can use their example to create a Redis cache. Keep in mind, we need the full Redis URL here, including the schmeredis://
, just the host won't work.
- Inconsistencies in the API using cache-managers
multiCache
: While creating a cache withcaching(...)
, which returns aPromise<MemoryCache>
,multiCache(...)
is only accepting Cache objects as parameters, no promises. So we either have to wait until the caches are created, or wrapping it intoPromise.all(...)