@gis-ag/oniyi-http-plugin-cache-redis
Version:
Plugin responsible for caching responses into redis db
81 lines (70 loc) • 2.6 kB
JavaScript
;
// node core modules
// 3rd party modules
const _ = require('lodash');
const OniyiCache = require('oniyi-cache');
const debug = require('debug')('oniyi-http-plugin:cache');
// internal modules
const buildRedisClient = require('./build-redis-client');
const phaseListsFactory = require('./phase-lists');
const defaultPluginOptions = {
ttl: 60 * 60 * 24 * 7, // default cache expiration time is limited to 1 week
minTtl: 60 * 60, // minimum time to live
delayCaching: false, // by default, we should cache response synchronously.
redis: {
host: '127.0.0.1',
port: 6379,
retry_strategy: (options) => {
if (options.error) {
const { code, message } = options.error;
if (code === 'ECONNREFUSED') {
// End reconnecting on a specific error and flush all commands with a individual error
return new Error(message || 'The server refused the connection');
}
if (code === 'ECONNRESET') {
return new Error(message || 'The server reset the connection');
}
if (code === 'ETIMEDOUT') {
return new Error(message || 'The server timed-outed the connection');
}
if (code === 'ENOENT') {
return new Error(message || 'Please provide valid UNIX socket string of the Redis server');
}
if (code === 'ENOTFOUND') {
return new Error(message || 'The server host/port not found');
}
}
if (options.total_retry_time > 1000 * 60 * 60) {
// End reconnecting after a specific timeout and flush all commands
// with a individual error
return new Error('Retry time exhausted');
}
if (options.attempt > 5) {
// End reconnecting with built in error
return undefined;
}
const reconnectionTime = Math.min(options.attempt * 1000, 7000);
debug(
'Failed to connect to redis server. Attempt number [%d]\n Attempt to reconnect in [$d] seconds',
options.attempt,
Math.round(reconnectionTime / 1000)
);
// reconnect after
return reconnectionTime;
},
},
};
/**
*/
const pluginFactory = (pluginOptions = {}) => {
const options = _.merge({}, defaultPluginOptions, pluginOptions);
const redisClient = buildRedisClient(options.redis);
const cache = new OniyiCache(Object.assign(options, { redisClient }));
const { requestHooks, responseHooks } = phaseListsFactory(cache, options);
return {
name: 'cache-redis',
onRequest: requestHooks,
onResponse: responseHooks,
};
};
module.exports = pluginFactory;