1
\$\begingroup\$

I'm trying to create a class to connect to Redis in Express. I don't think my code is good enough as I got variable db hanging out.

'use strict';

var redis = require('redis');
var bluebird = require('bluebird');
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);

var debug = require('debug')('expressapp');

var config = require('../config');

var state = {
  db: null
};

module.exports = {
  connect: function connect(done) {
    if (state.db) {
      return done();
    }
    var client = redis.createClient({
      host: config.redis.url,
      port: config.redis.port,
      retry_strategy: function redisRetry(options) {
        if (options.error.code === 'ECONNREFUSED') {
          debug('Redis connection refused: ' + options.error.code);
        }
        if (options.total_retry_time > 1000 * 60 * 60) {
          return new Error('Retry time exhausted');
        }

        return Math.max(options.attempt * 100, 2000);
      }
    });

    client.on('error', function redisError(err) {
      debug('Redis error' + err);
      return new Error(err);
    });

    client.on('reconnecting', function redisReconnecting() {
      debug('Retrying to connect to Redis');
    });

    client.on('connect', function redisConnect() {
      debug('Redis connected');
      state.db = client;
      done()
    });
  },

  get: function get() {
    return state.db;
  },

  close: function close(done) {
    if (state.db) {
      state.db.quit();
      return done();
    }
  }
}

I would really appreciated any suggestions.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.