LeagueStats/server/app/Services/Jax/src/JaxRequest.js

58 lines
1.4 KiB
JavaScript
Raw Normal View History

const { promisify } = require('util')
const Redis = use('Redis')
2019-08-24 14:56:55 +00:00
class JaxRequest {
constructor(region, config, endpoint, limiter, cacheTime) {
this.region = region
2019-09-26 19:20:27 +00:00
this.config = config
2019-08-24 14:56:55 +00:00
this.endpoint = endpoint
this.limiter = limiter
this.cacheTime = cacheTime
2019-09-26 19:20:27 +00:00
this.retries = config.requestOptions.retriesBeforeAbort
this.sleep = promisify(setTimeout)
2019-08-24 14:56:55 +00:00
}
async execute() {
const url = `https://${this.region}.api.riotgames.com/lol/${this.endpoint}`
// Redis cache
if (this.cacheTime > 0) {
const requestCached = await Redis.get(url)
if (requestCached) {
return JSON.parse(requestCached)
}
}
2019-08-24 14:56:55 +00:00
try {
const resp = await this.limiter.executing({
url,
2019-09-26 19:20:27 +00:00
token: this.config.key,
2019-08-24 14:56:55 +00:00
resolveWithFullResponse: false
})
if (this.cacheTime > 0) {
await Redis.set(url, resp, 'EX', this.cacheTime)
}
2019-08-24 14:56:55 +00:00
return JSON.parse(resp)
} catch ({ statusCode, ...rest }) {
2019-09-26 19:20:27 +00:00
this.retries--
2019-09-26 19:22:45 +00:00
if (statusCode !== 503 && statusCode !== 500) return
2019-09-26 19:20:27 +00:00
console.log('====================================')
console.log(statusCode)
console.log('====================================')
if (this.retries > 0) {
await this.sleep(this.config.requestOptions.delayBeforeRetry)
return this.execute()
2019-09-26 19:20:27 +00:00
}
2019-08-24 14:56:55 +00:00
}
}
}
module.exports = JaxRequest