title: NodeJS restify API caching best practice
body: <p>I am very new to NodeJS and I am building my first API using restify.
  I want to find out what is best practice for caching the response data - each API call must have its own cache time.</p>
  
  <p>I have looked at res.cache() but that seems to be only per user request and not a global application cache. </p>
  
  <p>I then looked at <a href="https://www.npmjs.com/package/restify-cache" rel="nofollow">restify-cache</a> but the documentation did not clearly tell me how to use it.</p>
  
  <p>My application works like this:</p>
  
  <p>server.js code:</p>
  
  <pre><code>var restify = require('restify');
  var mysqlDB = require('./config/connection');
  
  // REST server declaration and configuration
  var server = restify.createServer({
    name: 'test-api',
    version: '0.0.1'
  });
  
  server.pre(restify.pre.sanitizePath());
  server.use(restify.queryParser());
  server.use(restify.acceptParser(server.acceptable));
  server.use(restify.queryParser());
  server.use(restify.bodyParser());
  
  server.listen(9007, function() {
    console.log('%s listening at %', server.name, server.url);
    mysqlDB.handleDisconnect();
    console.log(new Date() +': Started Cricket API on port 9007');
  });
  
  var routes = require('./routes')(server);
  </code></pre>
  
  <p>routes.js code:</p>
  
  <pre><code>module.exports = function(app) {
  app.get('/', function(req, res, next) {
      return res.send("You have reached the test API");
  });
  
  var fixtures = require('./controllers/fixtures');
      app.get('/getfixtures', fixtures.getFixtures);  // Get All Fixtures
  };
  </code></pre>
  
  <p>fixtures.js code snippet:</p>
  
  <pre><code>this.getFixtures = function (req, res, next) {
  
  res.header("Access-Control-Allow-Origin", "*"); 
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  
  console.log("Get All Fixtures");
  var mysql = mysqlDB.getConnection();
  
  var query = "SELECT * FROM fixtures WHERE fixture_date &gt;= CURDATE() ORDER BY fixture_date, fixture_time";          
        mysql.query(query,function(err,rows){
          if(err) {
              var status = mysqlDB.getErrorStatus(err.code);
              return res.status(status.code).send("Error : "+ status.Message);                  
          } else {
            var data = [];
            for (i in rows){
              var item = rows[i];
  
              var output = util.formatDate(item.fixture_date);
              item.fixture_date = output;
  
              data.push(item);
            };
  
            return res.send(data);
          }
        });
    };
  </code></pre>
  
  <p>Can someone please send me in the right direction? I don't know where to add the caching part?</p>