title: How to cache query data in node with redis
body: <p>I´m building an API in Node with Express, Postgresql and Redis and I´m a complete beginner when it comes to node. I´m trying to setup redis to cache the query response from postgres but I just can´t figure out how to do it without repeating the implementation in every file.</p>
  
  <p>Here´s some of my app.js</p>
  
  <pre><code>// connect to the postgresql database 
  var database = require("./config/database")(app);
  var pg = require("pg"); 
  var conString = app.get('db uri');
  var client = new pg.Client(conString); client.connect();
  
  // an example of how my routes look like
  app.get('/v1/users/:uid', users.getUser(client));
  </code></pre>
  
  <p>Here´s users.js</p>
  
  <pre><code>exports.getUser = function(client) {
      return function(req, res) {
      var userId = req.params.uid;
  
      var query = client.query("SELECT * FROM users WHERE users.id = ?",[userId]);
  
      query.on("row", function (row, result) {
        result.addRow(row);
      });
  
      query.on("end", function (result) {
        res.json(result.rows);
      });
  
    };
  };
  </code></pre>
  
  <p>Ive searched all over the web including stackoverflow and the closest solution I´ve found can be found on this page <a href="http://blog.stevenlu.com/2013/03/07/using-redis-for-caching-in-nodejs/" rel="nofollow">using redis for cahing in node</a>
  His solution looks like this:</p>
  
  <pre><code>var handler = function(response)
  {
     response = JSON.stringify(response);
     client.setex('some-key-value', 21600, response);     
     res.end(response);
  };
  
  client.get('some-key-value', function (err, result) {
     if (err || !result)
        execute_function(zipcode, handler);
     else
        res.end(result);
  });
  </code></pre>
  
  <p>I´ve got it sort of working by wrapping everything inside the client.get if/else statement but it looks ugly and since I have many routes I would end up repeating alot of code, any help of how I can get this solution working with my code would be really appreciated. Thanks in advance!</p>