Last active
July 27, 2016 18:42
-
-
Save bhague1281/24bfc29c76ae00c4f9d3f1251f943f08 to your computer and use it in GitHub Desktop.
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
const request = require('request'); | |
const NodeCache = require('node-cache'); | |
const API_ENDPOINT = 'http://pokeapi.co/api/v2/pokemon/'; | |
const cache = new NodeCache(); | |
// accepts an endpoint (string) to query | |
// accepts a callback function to be called when the query is finished | |
function callEndpoint(endpoint, callback) { | |
request(endpoint, (error, response, body) => { | |
// if unsuccessful, pass the error to the callback function | |
if (error || response.statusCode !== 200) return callback(error, null); | |
// if successful, store the body in the cache | |
cache.set(endpoint, body, (err, success) => { | |
// if unsuccessful, pass the error to the callback function | |
if (err || !success) return callback(err, null); | |
// if successful, pass no error and the request body to the callback function | |
return callback(null, body); | |
}); | |
}); | |
} | |
// accepts an endpoint (string) to query | |
// accepts a callback function to be called when the query is finished | |
function requestCache(endpoint, callback) { | |
// try getting cached data from the cache first | |
cache.get(endpoint, (err, cachedData) => { | |
// if there's an error, pass the error to the callback function | |
if (err) return callback(err, null); | |
// if there's cached data, pass no error and the cached data to the callback function | |
if (cachedData) return callback(null, cachedData); | |
// if no error and data was not found, make the API request and pass the callback function | |
callEndpoint(endpoint, callback); | |
}); | |
} | |
// Calling requestCache with the PokeAPI endpoint. Note how this is similar to how request is called | |
requestCache(API_ENDPOINT, (err, data) => console.log(data)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment