lol-api-client
Version:
A Node client for interfacing with the League of Legends API
30 lines (26 loc) • 1.04 kB
JavaScript
const request = require('request')
// Instantiate a new Promise and pass the resolve/reject callbacks
// to the helper method below that handles recursive retries.
exports.makeRequest = function (url) {
return new Promise((resolve, reject) => {
recursiveRequest(url, resolve, reject)
})
}
// Helper that will recursively retry if the response from Riot's API
// tells us that we've exceeded the rate limit for the user's API key.
// This is sort of hacky and passing around the resolve/reject callbacks
// seems like bad convention - this was just difficult to implement a
// retry loop within a promise.
function recursiveRequest (url, resolve, reject) {
request(url, (error, response, body) => {
if (!error && response.statusCode === 200) {
resolve(JSON.parse(body))
} else if (response.statusCode === 429) {
const delay = (parseInt(response.headers['retry-after'], 2) + 3) * 1000
setTimeout(recursiveRequest, delay, url, resolve, reject)
} else {
reject(response)
}
})
}