@gis-ag/oniyi-http-plugin-cache-redis
Version:
Plugin responsible for caching responses into redis db
71 lines (59 loc) • 2.02 kB
JavaScript
;
// node core modules
// 3rd party modules
const _ = require('lodash');
const redis = require('redis');
const debug = require('debug')('oniyi-http-plugin:cache:make-redis-client');
// internal modules
const validRedisOptions = [
'unixSocket', // if this is presented, host and port are ignored
'host',
'port',
'path',
'url',
'db',
'tls',
'prefix',
'retry_strategy',
'return_buffers',
'detect_buffers',
'socket_nodelay',
'socket_keepalive',
'no_ready_check',
'enable_offline_queue',
'retry_unfulfilled_commands',
'auth_pass',
'family',
'disable_resubscribing',
'rename_commands',
];
const createRedisClient = (redisOptions = {}) => {
const { unixSocket, host, port } = redisOptions;
if (unixSocket) {
debug('creating redis client with unixSocket configuration: ', unixSocket);
return redis.createClient(unixSocket, redisOptions);
}
debug('creating redis client for host [%s] and port [%d]', host, port);
return redis.createClient(port, host, redisOptions);
};
/**
* This method builds a redisClient according to the provided params. Also selects any specified database
*
* @param {Object} params An object literal with the redis options you want to set on the client including connection parameters (host + ip or unix socket)]
* @return {[redisClient]} The redis client created with the provided options
*/
function buildRedisClient(params) {
const redisOptions = _.pick(params, validRedisOptions);
const redisClient = createRedisClient(redisOptions);
redisClient.on('ready', () => {
debug('redis client for host [%s] and port [%d] is ready', redisOptions.host, redisOptions.port);
});
redisClient.on('connect', () => {
debug('redis client for host [%s] and port [%d] is connected', redisOptions.host, redisOptions.port);
if (redisClient.selected_db) {
debug('redis client selected database [%d]', redisClient.selected_db);
}
});
return redisClient;
}
module.exports = buildRedisClient;