11const helper = require ( './helper' ) ;
22
3- function api ( baseUrl , config , method , params ) {
3+ async function api ( baseUrl , config , method , params ) {
44 const url = new URL ( baseUrl ) ;
55 const auth = Buffer . from ( `${ config . username } :${ config . apiKey } ` ) . toString (
66 'base64'
@@ -21,32 +21,28 @@ function api(baseUrl, config, method, params) {
2121 url . searchParams . append ( key , value ) ;
2222 } ) ;
2323 }
24- let response = null ;
25- return helper
26- . fetch ( url . href , options )
27- . then ( ( res ) => {
28- response = res ;
29- return res . json ( ) ;
30- } )
31- . catch ( ( e ) => {
32- if ( e instanceof SyntaxError ) {
33- // We probably got a non-JSON response from the server.
34- // We should inform the user of the same.
35- let message = 'Server Returned a non-JSON response.' ;
36- if ( response . status === 404 ) {
37- message += ` Maybe endpoint: ${ method } ${ response . url . replace (
38- config . apiURL ,
39- ''
40- ) } doesn't exist.`;
41- } else {
42- message += ' Please check the API documentation.' ;
43- }
44- const error = new Error ( message ) ;
45- error . res = response ;
46- throw error ;
24+ const response = await helper . fetch ( url . href , options ) ;
25+ try {
26+ return response . json ( ) ;
27+ } catch ( e ) {
28+ if ( e instanceof SyntaxError ) {
29+ // We probably got a non-JSON response from the server.
30+ // We should inform the user of the same.
31+ let message = 'Server Returned a non-JSON response.' ;
32+ if ( response . status === 404 ) {
33+ message += ` Maybe endpoint: ${ method } ${ response . url . replace (
34+ config . apiURL ,
35+ ''
36+ ) } doesn't exist.`;
37+ } else {
38+ message += ' Please check the API documentation.' ;
4739 }
48- throw e ;
49- } ) ;
40+ const error = new Error ( message ) ;
41+ error . res = response ;
42+ throw error ;
43+ }
44+ throw e ;
45+ }
5046}
5147
5248module . exports = api ;
0 commit comments