Caches the returned value of promises in the provided redis cache
npm install redis-json-memoizeCaches the JSON response of a provided promise into the provided Redis. Ideal for caching responses from database calls in your API.
If you are looking to reap the benefits of Redis caching in your API, this library provides a simple and easy-to-use solution.
Compatible with both ioredis and node redis.
For more info on Redis: https://redis.io/topics/introduction
npm install --save redis-json-memoize
``
const Redis = require('ioredis');
const redisMemoize = require('redis-json-memoize');
const config = require('../../config');
const UserModel = require('../models/user'); // Could be from Mongoose, Sequelize etc
const redisInstance = new Redis(config.redisUrl);
function getUserByName(userName) {
return UserModel.find({ name: userName });
}
module.exports = redisMemoize.memoize(getUserByName, { redis: redisInstance });
`
`
const Redis = require('ioredis');
const redisMemoize = require('redis-json-memoize');
const config = require('../../config');
const UserModel = require('../models/user'); // Could be from Mongoose, Sequelize etc
const redisInstance = new Redis(config.redisUrl);
redisMemoize.initialize({
redis: redisInstance,
});
function getUserByName(userName) {
return UserModel.find({ name: userName });
}
module.exports = redisMemoize.memoize(getUserByName);
`
`
const Redis = require('ioredis');
const redisMemoize = require('redis-json-memoize');
const config = require('../../config');
const UserModel = require('../models/user'); // Could be from Mongoose, Sequelize etc
const redisInstance = new Redis(config.redisUrl);
redisMemoize.initialize({
redis: redisInstance,
});
function getUserByName(userName) {
return UserModel.find({ name: userName });
}
const cachedGetUserByName = redisMemoize.memoize(getUserByName);
module.exports = {
getUser: cachedGetUserByName,
clearCachedUsers: cachedGetUserByName.clearCache, // Will clear cached responses for this function only. Can accept a locator string.
}
`
- fn Provided function
- Must return a promise
- Should be named as specifically as possible (fn.name will be used to write the redis key for the cached response)fn.name
- NOTE: it is not recommended that you use this module to memoize Express/Hapi request handlers. Redis keys are written using a combination of and the function inputs stringified. HTTP requests are large circular objects, so the memoization will not be effectivememoizedFunction.clearCache
- fn.clearCache will clear Redis keys that were written memoizedFunction only. Similar to global clearCache` method, can accept a locator string.
- options
- redis This is where the Redis instance is provided. Compatible with both ioredis and node-redis.
- ttl Sets the TTL (time to loss) for responses memoized from this function. NOTE: Redis TTL's are in seconds, not milliseconds.