Skip to content

Instantly share code, notes, and snippets.

@srfrnk
Created October 9, 2014 16:59
Show Gist options
  • Save srfrnk/a67a44d6a77581668734 to your computer and use it in GitHub Desktop.
Save srfrnk/a67a44d6a77581668734 to your computer and use it in GitHub Desktop.
ExpressJS middleware to store data in a local cache on the servre for performance.
require("requirejs").define("models/localCache", [], function () {
var cache = require('memory-cache');
return function () {
return function (req, res, next) {
if (!!req.localCache) {
return next();
}
var sessionId = req.cookies["connect.sid"];
req.localCache = cache.get(sessionId) || {};
res.on('finish', function () {
cache.put(sessionId,req.localCache);
});
return next();
};
}
});
@srfrnk
Copy link
Author

srfrnk commented Oct 9, 2014

To use add to you app:
app.use(localCache())

where localCache is 'require'd using nodejs require of requirejs - whichever is best for you.

@srfrnk
Copy link
Author

srfrnk commented Oct 9, 2014

also add 'memory-cache' to your dependencies (i.e. via your package.json file) or using:
$ npm install --save memory-cache

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment