'use strict';

const path = require('path');
const bluebird = require('bluebird');
const redis = require("redis")
const _ = require('lodash');

bluebird.promisifyAll(redis.RedisClient.prototype);

function RedisCache(){
  var globalOptions = {
    port: 6379,
    host: 'localhost'
  };

  var isConnected = false;

  this.options = function(options) {
    if (options) {
      _.extend(globalOptions, options);
      return this;
    } else {
      return globalOptions;
    }
  };

  var isConnected = false;

  var client = connect()
    .on('error', console.log)
    .on('end', connect)
    .on('ready', ready)

  function ready(){
    console.log("redis is ready")
    isConnected = true;
  }

  function connect(){
    console.log("redis trying to connect");
    isConnected = false;
    return redis.createClient(globalOptions);
  }

  this.middlewares = function(options){
    options = options || {};

    return function(req, res, next){
      if(req.method != 'GET'){
        return next();
      }

      var key = req.url;

      client.getAsync(key)
        .then(function(cache){
          if( cache != null ){
            console.log("use cache")
            res.setHeader("X-Cached", "HIT");
            return res.send(JSON.parse(cache));

          }else{
            console.log("no cache");
            res.realSend = res.send;
            res.send = function(a, b) {
              console.log("add to cache")
              var data = !_.isUndefined(b) ? b : (!_.isNumber(a) ? a : null);
              console.log(data);
              client.set(key, data);
              client.EXPIRE(key, options.ttl); // in 15 minute.
              return res.realSend(data);
            };
            next()
          }
        })

      }
  }
}
module.exports = new RedisCache();

@@ -1123,45 +1123,8 @@
  )%7B%0A
-            console.log(%22use cache%22)%0A
     
@@ -1161,24 +1161,24 @@
 d%22, %22HIT%22);%0A
+
             
@@ -1235,45 +1235,8 @@
 se%7B%0A
-            console.log(%22no cache%22);%0A
     
@@ -1312,50 +1312,8 @@
 ) %7B%0A
-              console.log(%22add to cache%22)%0A
     
@@ -1390,41 +1390,8 @@
 l);%0A
-              console.log(data);%0A
     

remove print out