Last active
September 13, 2019 12:14
-
-
Save kkamkou/4351835 to your computer and use it in GitHub Desktop.
express.js caching (middleware)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @category Application | |
* @package Middleware | |
* @author Kanstantsin A Kamkou ([email protected]) | |
*/ | |
// 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(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why not check if expires in get method, use setTimeout in set method will generate too much timeout if set too much keys