Advanced cache based on ioredis, redlock and node-cache
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
How to use RedisCache
const advancedCache = const RedisCache = advancedCacheRedisCache const CachePolicy = advancedCacheCachePolicy const ioRedisOpts = port: 6379 host: '127.0.0.1' password: 'auth' keyPrefix: 'some:' const redlockOpts = retryCount: 0 //default const opts = lockIntervalMs: 1000 //time in ms key is locked to load data from store (default) retryIntervalMs: 50 //time failed lock waits before next try (default) const cache = ioRedisOpts opts redlockOpts //opts and redlockOpts are optional and have defaults //string value const countryCachePolicy = 'country-code' 5 24 * 60 * 60 cache //js object as JSON const userCachePolicy = 'user' 12 60 * 60 cache //js object as hash cache //when you need direct access to redis client cacheredis
How to use MemoryCache
const advancedCache = const MemoryCache = advancedCacheMemoryCache //extended from NodeCache const CachePolicy = advancedCacheCachePolicy const opts = useClones: false //default opts const cache = opts const countryCachePolicy = 'country-code' 5 24 * 60 * 60 cache
How to bypass cache
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