2019-10-21 18:05:17 +00:00
|
|
|
const { promisify } = require('util')
|
2020-04-26 18:07:17 +00:00
|
|
|
const Redis = use('Redis')
|
2019-10-21 18:05:17 +00:00
|
|
|
|
2019-08-24 14:56:55 +00:00
|
|
|
class JaxRequest {
|
2020-04-26 18:07:17 +00:00
|
|
|
constructor(region, config, endpoint, limiter, cacheTime) {
|
2019-12-02 19:41:05 +00:00
|
|
|
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
|
2020-04-26 18:07:17 +00:00
|
|
|
this.cacheTime = cacheTime
|
2019-09-26 19:20:27 +00:00
|
|
|
this.retries = config.requestOptions.retriesBeforeAbort
|
2019-10-21 18:05:17 +00:00
|
|
|
|
|
|
|
|
this.sleep = promisify(setTimeout)
|
2019-08-24 14:56:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async execute() {
|
2020-04-26 18:07:17 +00:00
|
|
|
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({
|
2020-04-26 18:07:17 +00:00
|
|
|
url,
|
2019-09-26 19:20:27 +00:00
|
|
|
token: this.config.key,
|
2019-08-24 14:56:55 +00:00
|
|
|
resolveWithFullResponse: false
|
|
|
|
|
})
|
|
|
|
|
|
2020-04-26 18:07:17 +00:00
|
|
|
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) {
|
2019-10-21 18:05:17 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
2019-09-11 07:06:21 +00:00
|
|
|
module.exports = JaxRequest
|