UNPKG

@apicart/core-sdk

Version:

Apicart Core dependency for all SDKs

74 lines (59 loc) 1.79 kB
import Utils from '@apicart/js-utils'; class ApiCommunicator { private call( url: string, query: string, variables: Record<string, any>, connectTimeout: 5000, withCredentials: boolean ): Promise<any> { return Utils.Ajax .post(url, { data: Utils.Json.stringify({ query: query, variables: variables }), headers: { 'Content-Type': 'application/json' }, withCredentials: withCredentials, timeout: connectTimeout }) .then((response: any) => { if (response.status === 401) { throw '401 Unauthorized - check provided Payments API token'; } else if (response.status === 404) { throw '404 Not Found - data source was not found'; } else if (response.status === 429) { throw '429 Too Many Requests - read rate limit docs section'; } else if (response.status !== 200) { throw response.status + ' - please contact Apicart support'; } return response; }) .catch((error: string) => { Utils.Console.error(error); }); } public isSuccessResult(response: any | null = null, key: string, throwOnFailed = true): boolean { if (response === null) { throw 'An error occurred, please try again in a few minutes.'; } if (Utils.Validators.isEmpty(response)) { throw 'Response is empty.'; } const responseData = response.data; if (!Utils.Objects.keyExists(responseData, 'data.' + key + '.result')) { throw 'Response doesn\'t contains valid result.'; } if (throwOnFailed && responseData.data[key].result !== 'SUCCESS') { throw Utils.Strings.sprintf( 'Response returned result "%0%" with message "%1%".', [responseData.data[key].result, responseData.data[key]['message'] || ''] ); } return true; } } export default new ApiCommunicator();