Skip to content

Instantly share code, notes, and snippets.

@bhague1281
Last active July 27, 2016 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhague1281/6c5f9c05725bb8575fc86b4e88d22b47 to your computer and use it in GitHub Desktop.
Save bhague1281/6c5f9c05725bb8575fc86b4e88d22b47 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('my-pokemon', (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('my-pokemon', 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