Main points to have this module are:
- reduce load on data storage on cold start
- unify repetitive actions as: get from cache if not load from db
- reload cache before it expires
Note: caches value only if result of load function is converted to true: !!result === true
constadvancedCache=require('advanced-cache')constRedisCache=advancedCache.RedisCacheconstCachePolicy=advancedCache.CachePolicyconstioRedisOpts={port: 6379,host: '127.0.0.1',password: 'auth',keyPrefix: 'some:'}constredlockOpts={retryCount: 0//default}constopts={lockIntervalMs: 1000,//time in ms key is locked to load data from store (default)retryIntervalMs: 50//time failed lock waits before next try (default)}constcache=newRedisCache(ioRedisOpts,opts,redlockOpts)//opts and redlockOpts are optional and have defaults//string valueconstcountryCachePolicy=newCachePolicy(['country-code',5],24*60*60)cache.stringFetch(countryCachePolicy,loadAsStringFnPromise,loadFnArgs).then(countryCode=>{})//js object as JSONconstuserCachePolicy=newCachePolicy(['user',12],60*60)cache.serializedFetch(userCachePolicy,loadAsObjectFnPromise,loadFnArgs).then(user=>user.fly())//js object as hashcache.hashFetch(userCachePolicy,loadAsObjectFnPromise,loadFnArgs).then(user=>user.fly())//when you need direct access to redis clientcache.redis.mget(['country-code:13','user:12']).then(()=>{})constadvancedCache=require('advanced-cache')constMemoryCache=advancedCache.MemoryCache//extended from NodeCacheconstCachePolicy=advancedCache.CachePolicyconstopts={useClones: false}//default optsconstcache=newMemoryCache(opts)constcountryCachePolicy=newCachePolicy(['country-code',5],24*60*60)cache.fetch(countryCachePolicy,loadPromise).then(countryCode=>{})Sometimes during development it handy just bypass cache and fetch data directly from load function
To bypass RedisCache add environment variable ADVANCED_CACHE_BYPASS_REDIS_CACHE equal to 1
To bypass MemoryCache add environment variable ADVANCED_CACHE_BYPASS_MEMORY_CACHE equal to 1
Though it will work only if your NODE_ENV equals development