Skip to content

Instantly share code, notes, and snippets.

@alfg
Last active August 29, 2015 14:25
Show Gist options
  • Save alfg/532d02568767435229d7 to your computer and use it in GitHub Desktop.
Save alfg/532d02568767435229d7 to your computer and use it in GitHub Desktop.
node-cache getOrSet caching pattern.
var NodeCache = require('node-cache');
var myCache = new NodeCache();
var cache = {
/** Gets key from cache if exists, else sets the cache and returns data.
* @param {string} cacheKey - Key to get or set.
* @param {integer} timeout - Timeout (in seconds) for cache to release.
* @param {Function} fn - Function to get data if key does not exist.
* @param {Function} callback - Callback function to send back data or value.
*/
getOrSet: function(cacheKey, timeout, fn, callback) {
myCache.get(cacheKey, function(err, value) {
if (!err) {
if (value == undefined) {
fn(function(data) {
myCache.set(cacheKey, data, timeout);
callback(data);
});
} else {
callback(value);
}
}
});
}
}
module.exports = cache;
var express = require('express');
var cache = require('./cache');
var router = express.Router();
var Spotify = require('./spotify');
router.get('/playlists', function(req, res) {
var cacheKey = 'featured_playlists';
var timeout = 60 * 15; // 15 minutes.
cache.getOrSet(cacheKey, timeout, getFeaturedPlaylists, function(data) {
res.json({data: data});
});
// Cache function.
function getFeaturedPlaylists(callback) {
// Get playlists.
var spotifyService = new Spotify();
spotifyService.getFeaturedPlaylists(function(data) {
callback(data);
});
}
});
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment