Skip to content

Instantly share code, notes, and snippets.

@kkamkou
Last active September 13, 2019 12:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkamkou/4351835 to your computer and use it in GitHub Desktop.
Save kkamkou/4351835 to your computer and use it in GitHub Desktop.
express.js caching (middleware)
/**
* @category Application
* @package Middleware
* @author Kanstantsin A Kamkou (kkamkou@gmail.com)
*/
// tiny caching engine
var Dejavu = function () {
// default cache holder
this._cache = [];
/**
* Returns the cached key
*
* @param {String} key
* @return {Mixed|null}
*/
this.get = function (key) {
return this._cache[key] || null;
};
/**
* Checks if cache has such key
*
* @param {String} key
* @return {Boolean}
*/
this.has = function (key) {
return !!this._cache[key];
};
/**
* Stores data to the cache set
*
* @param {String} key
* @param {Mixed} data
* @param {Number} seconds
* @return {Dejavu}
*/
this.set = function (key, data, seconds) {
// cache set
this._cache[key] = data;
// cache cleanup
seconds = parseInt(seconds, 10);
if (seconds > 0) {
setTimeout(function () { this.cleanup(key); }.bind(this), seconds * 1000);
}
// chaining
return this;
};
/**
* Key cleanup
*
* @param {String} key
* @return {Dejavu}
*/
this.cleanup = function (key) {
// key cleanup
if (!delete this._cache[key]) {
this._cache[key] = null;
}
// chaining
return this;
};
};
// exporting stuff
module.exports = function (req, res, next) {
// we have it
if (req.app.get('dejavu')) {
return next();
}
// adding the cache engine to the settings
req.app.set('dejavu', new Dejavu());
// jumping up
next();
};
@kkamkou
Copy link
Author

kkamkou commented Dec 21, 2012

This middleware is similar to the memcache, but uses the express.js as ancestor.

req.app.get('dejavu').set('myBigFunctionData', myBigFunction()); // storing
req.app.get('dejavu').has('myBigFunctionData'); // boolean
req.app.get('dejavu').get('myBigFunctionData'); // your data

req.app.get('dejavu').set('myBigFunctionData', myBigFunction(), 3600); // expiration

@lzyzsd
Copy link

lzyzsd commented Jul 23, 2013

why not check if expires in get method, use setTimeout in set method will generate too much timeout if set too much keys

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