Last active
August 29, 2015 14:25
-
-
Save alfg/532d02568767435229d7 to your computer and use it in GitHub Desktop.
node-cache getOrSet caching pattern.
This file contains 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
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; |
This file contains 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
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