Create a gist now

Instantly share code, notes, and snippets.

@kkamkou /dejavu.js
Last active Dec 10, 2015

Embed
What would you like to do?
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

This comment has been minimized.

Show comment
Hide comment
@kkamkou

kkamkou 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
Owner

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

This comment has been minimized.

Show comment
Hide comment
@lzyzsd

lzyzsd 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

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