kwhitley / apicache

Simple API-caching middleware for Express/Node.
MIT License
1.24k stars 193 forks source link

Path not being cached #7

Closed genebean closed 8 years ago

genebean commented 10 years ago

I've tried following your instructions and I think I've done it right yet nothing is getting cached. Am I doing something wrong or is this a bug? Below is the code in which I am trying to use your cache. You'll see one line with req.apicacheGroup commented out. I'd like to use this but disabled it in trying to debug stuff. The response given is a page full of JSON (not just a single key: value). Thanks for any insight you can provide.

var apicache  = require('apicache').options({ debug: true }).middleware;
var converter = require('csvtojson').core.Converter;
var express   = require('express');
var request   = require('request');
var router    = express.Router();

/* 
 *  GET home page.
 */
router.get('/', function(req, res) {
  res.render('index');
});

/*
 *  Routes per school
 */

// Pull in the file(s) from each school
var westga = require('./schools/westga');

// westga's routes
router.get('/westga/bulletin/:term', apicache('60 minutes'), function(req, res) {
  //req.apicacheGroup = req.params.term
  var term = req.params.term;
  if ( westga.validTerms.indexOf(term) >= 0 ) {
    res.writeHead(200, {"Content-Type": "application/json"});
    switch (term) {
      case 'fall':
        var url = westga.bulletin + westga.fall;
        break;
      case 'spring':
        var url = westga.bulletin + westga.spring;
        break;
      case 'summer':
        var url = westga.bulletin + westga.summer;
        break;
      default:
        console.log('Something went wrong...');
    }
    // Don't save everything to memory. This facilitates large CSV's
    var csvConverterForWestgaBulletin = new converter({constructResult:false});
    console.log(url);
    request.get(url).pipe(csvConverterForWestgaBulletin).pipe(res);
  } else {
    res.status(404);
    res.render('404.jade', {title: '404: File Not Found'});
    console.log('invalid term provided');
  }
});

router.get('/westga/catalog', apicache('1 month'), function(req, res) {
  var url = westga.catalog + westga.currentCatalog;
  // Don't save everything to memory. This facilitates large CSV's
  var csvConverterForWestgaCatalog = new converter({constructResult:false});
  console.log(url);
  res.writeHead(200, {"Content-Type": "application/json"});
  request.get(url).pipe(csvConverterForWestgaCatalog).pipe(res);
});

module.exports = router;
andrewho83 commented 9 years ago

I had a similar issue, but found that I wasn't writing anything to the response, and once I did, caching worked again.

kwhitley commented 8 years ago

Correct... nothing will be cached until the final write is attempted.