All files / base base.ts

83.81% Statements 88/105
71.43% Branches 45/63
91.67% Functions 11/12
83.65% Lines 87/104

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 2405x 5x   5x     5x 5x 5x 5x 5x 5x 5x     5x 20x 20x     20x 20x 20x                           20x 20x 6x 14x 6x 4x   6x         6x 3x   6x 3x   6x                     6x 6x     6x         8x                       10x               10x 10x 10x 10x     10x 11x 11x 11x 11x   10x       12x         12x 12x       6x         6x 6x       6x 6x 4x   2x 2x                     4x 4x 4x 2x   2x 2x 2x 2x     2x   2x               2x   2x     2x   2x       2x       2x       1x                   9x 1x     8x 8x   8x   8x     8x                 8x     8x 8x 2x 2x         6x 2x   4x   8x            
import * as _ from 'lodash'
import { ApiKeyNotFound } from '../errors'
import { IEndpoint } from '../endpoints'
import { TOO_MANY_REQUESTS, SERVICE_UNAVAILABLE } from 'http-status-codes'
import { ApiResponseDTO } from '../models-dto/api-response/api-response'
import { RateLimitDto } from '../models-dto/rate-limit/rate-limit.dto'
import { GenericError } from '../errors/Generic.error'
import { RateLimitError } from '../errors/rate-limit.error'
import { IBaseApiParams, IParams, waiter } from './base.utils'
import { ServiceUnavailable } from '../errors/service-unavailable.error'
import { BaseConstants, BaseApiGames } from './base.const'
import { Logger } from './logger.base'
import { RequestBase } from './request.base'
import { AxiosRequestConfig } from 'axios'
 
export class BaseApi<Region extends string> {
  protected readonly game: BaseApiGames = BaseApiGames.LOL
  private readonly baseUrl = BaseConstants.BASE_URL
  private key: string
  private concurrency: number | undefined
  private rateLimitRetry: boolean = true
  private rateLimitRetryAttempts: number = BaseConstants.RETRY_ATTEMPTS
  private debug = {
    logTime: false,
    logUrls: false,
    logRatelimits: false
  }
 
  constructor ()
  constructor (params: IBaseApiParams)
  /**
   * Base api
   * @param key Riot games api key
   */
  constructor (key: string)
  constructor (param?: string | IBaseApiParams) {
    this.key = ''
    if (typeof param === 'string') {
      this.key = param
    } else if (param) {
      if (typeof param.key === 'string') {
        this.key = param.key
      }
      this.setParams(param)
    }
  }
 
  private setParams (param: IBaseApiParams) {
    if (typeof param.rateLimitRetry !== 'undefined') {
      this.rateLimitRetry = param.rateLimitRetry
    }
    if (typeof param.rateLimitRetryAttempts !== 'undefined') {
      this.rateLimitRetryAttempts = param.rateLimitRetryAttempts
    }
    Iif (typeof param.debug !== 'undefined') {
      if (typeof param.debug.logTime !== 'undefined') {
        _.set(this.debug, 'logTime', param.debug.logTime)
      }
      if (typeof param.debug.logUrls !== 'undefined') {
        _.set(this.debug, 'logUrls', param.debug.logUrls)
      }
      if (typeof param.debug.logRatelimits !== 'undefined') {
        _.set(this.debug, 'logRatelimits', param.debug.logRatelimits)
      }
    }
    this.concurrency = param.concurrency
    Iif (typeof param.concurrency !== 'undefined') {
      RequestBase.setConcurrency(param.concurrency)
    } else {
      RequestBase.setConcurrency(Infinity)
    }
  }
 
  private getRateLimits (headers: any): RateLimitDto {
    return {
      Type: _.get(headers, 'x-rate-limit-type', null),
      AppRateLimit: _.get(headers, 'x-app-rate-limit', null),
      AppRateLimitCount: _.get(headers, 'x-app-rate-limit-count', null),
      MethodRateLimit: _.get(headers, 'x-method-rate-limit'),
      MethodRatelimitCount: _.get(headers, 'x-method-rate-limit-count', null),
      RetryAfter: +_.get(headers, 'retry-after', 0),
      EdgeTraceId: _.get(headers, 'x-riot-edge-trace-id')
    }
  }
 
  private getBaseUrl () {
    return this.baseUrl.replace(':game', this.game)
  }
 
  private getApiUrl (endpoint: IEndpoint, params: IParams) {
    const {
      prefix,
      version,
      path
    } = endpoint
    const basePath = `${prefix}/v${version}/${path}`
    const re = /\$\(([^\)]+)?\)/g
    let base = `${this.getBaseUrl()}/${basePath}`
    let match
    // tslint:disable:no-conditional-assignment
    while (match = re.exec(base)) {
      const [key] = match
      const value = encodeURI(String(params[match[1]]))
      base = base.replace(key, value)
      re.lastIndex = 0
    }
    return base
  }
 
  private isRateLimitError (e: any) {
    Iif (!e) {
      return false
    }
    const {
      statusCode = e.status
    } = e || e.error
    return statusCode === TOO_MANY_REQUESTS
  }
 
  private isServiceUnavailableError (e: any) {
    Iif (!e) {
      return false
    }
    const {
      statusCode = e.status
    } = e || e.error
    return statusCode === SERVICE_UNAVAILABLE
  }
 
  private getError (e: any) {
    const headers = this.getRateLimits(_.get(e, 'response.headers'))
    if (this.isRateLimitError(e)) {
      return new RateLimitError(headers)
    }
    Eif (this.isServiceUnavailableError(e)) {
      return new ServiceUnavailable(headers, e)
    }
    // Otherwise generic error
    return new GenericError(headers, e)
  }
 
  private internalRequest<T> (config: AxiosRequestConfig): Promise<T> {
    return RequestBase.request<T>(config)
  }
 
  private async retryRateLimit<T> (region: Region, endpoint: IEndpoint, params?: IParams, e?: any): Promise<ApiResponseDTO<T>> {
    let baseError = this.getError(e)
    const isRateLimitError = this.isRateLimitError(e) || this.isServiceUnavailableError(e)
    if (!this.rateLimitRetry || !isRateLimitError || this.rateLimitRetryAttempts < 1) {
      throw baseError
    }
    const forceError = true
    for (let i = 0; i < this.rateLimitRetryAttempts; i++) {
      try {
        const response = await this.request<T>(region, endpoint, params, forceError)
        return response
      } catch (error) {
        const parseError = this.getError(error)
        // Isn't rate limit error
        Iif (!this.isRateLimitError(error) && !this.isServiceUnavailableError(error)) {
          throw parseError
        }
        // Set a new attemp
        const {
          rateLimits: {
            RetryAfter
          }
        } = parseError
        const waitSeconds =
          this.isServiceUnavailableError(e) ?
            BaseConstants.SERVICE_UNAVAILABLE :
            BaseConstants.RATE_LIMIT
        const msToWait = ((RetryAfter || 0) * 1000) + (waitSeconds * 1000 * Math.random())
        // Log
        Iif (this.debug.logRatelimits) {
          Logger.rateLimit(endpoint, msToWait)
        }
        // Wait
        await waiter(msToWait)
      }
    }
    // Throw rate limit
    throw baseError
  }
 
  protected getParam (): IBaseApiParams {
    return {
      key: this.key,
      rateLimitRetry: this.rateLimitRetry,
      rateLimitRetryAttempts: this.rateLimitRetryAttempts,
      concurrency: this.concurrency,
      debug: this.debug
    }
  }
 
  protected async request<T> (region: Region, endpoint: IEndpoint, params?: IParams, forceError?: boolean, queryParams?: any): Promise<ApiResponseDTO<T>> {
    if (!this.key) {
      throw new ApiKeyNotFound()
    }
    // Url params
    params = params || {}
    params.region = region.toLowerCase()
    // Format
    const url = this.getApiUrl(endpoint, params)
    // Logger
    Iif (this.debug.logTime) {
      Logger.start(endpoint, url)
    }
    const config: AxiosRequestConfig = {
      url,
      method: 'GET',
      headers: {
        Origin: null,
        'X-Riot-Token': this.key
      },
      params: queryParams,
    }
    Iif (this.debug.logUrls) {
      Logger.uri(config, endpoint)
    }
    try {
      const apiResponse = await this.internalRequest<any>(config)
      const { body, headers } = apiResponse
      return {
        rateLimits: this.getRateLimits(headers),
        response: body
      }
    } catch (e) {
      if (forceError) {
        throw e
      }
      return await this.retryRateLimit<T>(region, endpoint, params, e)
    } finally {
      Iif (this.debug.logTime) {
        Logger.end(endpoint, url)
      }
    }
  }
}