Skip to content

Instantly share code, notes, and snippets.

@bhague1281
Last active July 27, 2016 18:41
Show Gist options
  • Save bhague1281/731750a43cba20427a31ce4846dfc4c5 to your computer and use it in GitHub Desktop.
Save bhague1281/731750a43cba20427a31ce4846dfc4c5 to your computer and use it in GitHub Desktop.
const request = require('request');
const NodeCache = require('node-cache');
const API_ENDPOINT = 'http://pokeapi.co/api/v2/pokemon/';
const cache = new NodeCache();
// try getting data from the cache first
cache.get(API_ENDPOINT, (err, data) => {
// return early if there's an error or data is available
if (err) return console.log(err);
if (data) return console.log('Obtained data from cache:', data);
// if no error, but data was not found, make the API request
request(API_ENDPOINT, (error, response, body) => {
// if successful, store the body in the cache
if (!error && response.statusCode === 200) {
cache.set(API_ENDPOINT, body, (err, success) => {
// return early if there's an error or no success
if (err || !success) return console.log(err);
console.log('Queried API, stored data in cache', body);
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment