Skip to content

Instantly share code, notes, and snippets.

@sayuj1
Created June 30, 2020 04:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sayuj1/8b9f4cc4e5c7b61daabf9be2222f3458 to your computer and use it in GitHub Desktop.
Save sayuj1/8b9f4cc4e5c7b61daabf9be2222f3458 to your computer and use it in GitHub Desktop.
// Port, host and auth token of Redis server might be defined as environment
// variables. If not, fall back to defaults.
let redisPort = process.env.REDIS_PORT || 6379,
redisHost = process.env.REDIS_HOST || '127.0.0.1',
redisAuth = process.env.REDIS_AUTH || null,
redis = require('redis');
// Since we are waiting for the error event, we don't have to check for errors
// individually after each Redis command.
let onError = (error) => {
console.error('Error in Redis client: ' + error.message);
console.error(error.stack);
console.log('Exiting now because of error in Redis client');
// Our app doesn't work without DB. Exit.
process.exit(1);
};
let onConnect = () => {
console.log('Successfully connected to Redis ' + redisHost + ':' + redisPort);
};
// How to use this module:
// let redis = require('./redis');
// redis.set('key', 'value');
// redis.get('key', (err, value) => {
// console.log('Value: ' + value);
// });
//
// See http://redis.io/commands for available commands and
// https://github.com/mranney/node_redis for basic usage.
module.exports = exports = (() => {
// Create a new client and establish a connection to DB.
// We need to create a new Redis client every time we require this file since
// Redis clients can either be in subscriber or regular mode. Subscriber mode
// means only commands invloving basic pub-sub functionality are valid.
let redisClient = redis.createClient(redisPort, redisHost, {
auth_pass: redisAuth
});
redisClient.on('error', onError);
redisClient.on('connect', onConnect);
return redisClient;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment