11/* eslint-disable no-restricted-syntax */
22import axios , { AxiosError , AxiosInstance } from 'axios' ;
3- import { URLSearchParams } from 'url ' ;
3+ import rateLimit , { RateLimitedAxiosInstance } from 'axios-rate-limit ' ;
44import { version } from '../../package.json' ;
55import Client from '../client/Client' ;
66import FortniteAPIError from '../exceptions/FortniteAPIError' ;
77import InvalidAPIKeyError from '../exceptions/InvalidAPIKeyError' ;
88import MissingAPIKeyError from '../exceptions/MissingAPIKeyError' ;
9+ import { serializeParams } from '../util/util' ;
910import { FortniteAPIResponseData } from './httpStructs' ;
1011
1112class HTTP {
1213 public client : Client ;
1314 public axios : AxiosInstance ;
15+ public statsAxios : RateLimitedAxiosInstance ;
1416 constructor ( client : Client ) {
1517 this . client = client ;
1618
@@ -26,26 +28,45 @@ class HTTP {
2628 } : { } ,
2729 } ,
2830 } ) ;
31+
32+ this . statsAxios = rateLimit ( this . axios , {
33+ maxRequests : 3 ,
34+ perMilliseconds : 1100 + this . client . config . rateLimitExtraTimeout ,
35+ } ) ;
2936 }
3037
3138 public async fetch ( url : string , params ?: any ) : Promise < FortniteAPIResponseData > {
3239 try {
3340 const response = await this . axios ( {
3441 url,
3542 params,
36- paramsSerializer : ( p ) => {
37- const searchParams = new URLSearchParams ( ) ;
43+ paramsSerializer : serializeParams ,
44+ } ) ;
3845
39- for ( const [ key , value ] of Object . entries ( p ) ) {
40- if ( Array . isArray ( value ) ) {
41- for ( const singleValue of value ) searchParams . append ( key , singleValue ) ;
42- } else {
43- searchParams . append ( key , ( value as any ) ) ;
44- }
46+ return response . data ;
47+ } catch ( e ) {
48+ if ( e instanceof AxiosError && e . response ?. data ?. error ) {
49+ if ( e . response . status === 401 ) {
50+ if ( this . client . config . apiKey ) {
51+ throw new InvalidAPIKeyError ( url ) ;
52+ } else {
53+ throw new MissingAPIKeyError ( url ) ;
4554 }
55+ }
56+
57+ throw new FortniteAPIError ( e . response . data , e . config , e . response . status ) ;
58+ }
4659
47- return searchParams . toString ( ) ;
48- } ,
60+ throw e ;
61+ }
62+ }
63+
64+ public async fetchStats ( url : string , params ?: any ) : Promise < FortniteAPIResponseData > {
65+ try {
66+ const response = await this . statsAxios ( {
67+ url,
68+ params,
69+ paramsSerializer : serializeParams ,
4970 } ) ;
5071
5172 return response . data ;
0 commit comments