@@ -17,25 +17,7 @@ export class APIManager {
1717 path : Route < T > ,
1818 options ?: APIRequestOptions < T > ,
1919 ) : Promise < APIResponse < T > > {
20- const init = options || ( { } as RequestInit ) ;
21-
22- init . method = init . method || "GET" ;
23- init . headers = {
24- ...( init . headers || { } ) ,
25- Authorization : this . apiKey ,
26- } ;
27-
28- const url = new URL ( path , `${ this . baseUrl } /${ this . version } ` ) ;
29-
30- if ( "query" in init && init . query ) {
31- const query = new URLSearchParams ( init . query as Record < string , string > ) ;
32- url . search = query . toString ( ) ;
33- init . query = undefined ;
34- }
35-
36- if ( "body" in init && init . body && ! ( init . body instanceof Buffer ) ) {
37- init . body = JSON . stringify ( init . body ) ;
38- }
20+ const { url, init } = this . parseRequestOptions ( path , options ) ;
3921
4022 const response = await fetch ( url , init ) . catch ( ( err ) => {
4123 throw new SquareCloudAPIError ( err . code , err . message ) ;
@@ -49,29 +31,30 @@ export class APIManager {
4931 return data ;
5032 }
5133
52- async fetch < T > (
34+ private parseRequestOptions (
5335 path : string ,
54- options : RequestInit = { } ,
55- ) : Promise < APIPayload < T > > {
56- options . method = options . method || "GET" ;
57- options . headers = {
58- ...( options . headers || { } ) ,
36+ options ?: APIRequestOptions < APIEndpoint > ,
37+ ) {
38+ const init = options || ( { } as RequestInit ) ;
39+
40+ init . method = init . method || "GET" ;
41+ init . headers = {
42+ ...( init . headers || { } ) ,
5943 Authorization : this . apiKey ,
6044 } ;
6145
62- const res = await fetch (
63- `${ this . baseUrl } /${ this . version } /${ path } ` ,
64- options ,
65- ) . catch ( ( err ) => {
66- throw new SquareCloudAPIError ( err . code , err . message ) ;
67- } ) ;
46+ const url = new URL ( path , `${ this . baseUrl } /${ this . version } ` ) ;
6847
69- const data = await res . json ( ) ;
48+ if ( "query" in init && init . query ) {
49+ const query = new URLSearchParams ( init . query as Record < string , string > ) ;
50+ url . search = query . toString ( ) ;
51+ init . query = undefined ;
52+ }
7053
71- if ( ! data || data . status === "error" || ! res . ok ) {
72- throw new SquareCloudAPIError ( data ?. code || "COMMON_ERROR" ) ;
54+ if ( "body" in init && init . body && ! ( init . body instanceof Buffer ) ) {
55+ init . body = JSON . stringify ( init . body ) ;
7356 }
7457
75- return data ;
58+ return { url , init } ;
7659 }
7760}
0 commit comments