UNPKG

@xompass/sdk-cloud-api

Version:

Xompass Client for cloud-api

106 lines (93 loc) 2.75 kB
import axios, { AxiosError, AxiosResponse } from 'axios'; import { operation } from 'retry'; import logger from './XompassLogger'; import { XompassClient } from '../../XompassClient'; export interface HTTPResponse { data?: any; status?: number; statusText?: string; headers?: any; request?: any; [x: string]: any; } export class XompassHTTPError extends Error { public statusCode?: number; public code: string; constructor(response: HTTPResponse) { response = response || { data: null, status: 500, statusText: 'An unknown error has occurred', headers: {}, }; let message = response.statusText || 'An unknown error has occurred'; let code = 'UNKNOWN_ERROR'; if (response.data) { if (response.data.error) { message = response.data.error.message; code = response.data.error.code; } else { message = response.data; } } super(message); this.statusCode = response.status; this.code = code; } } export interface XompassHTTPOptions { method: 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH' | 'HEAD' | 'OPTIONS'; url: string; routeParams?: { [key: string]: string | number }; body?: any; headers?: { [key: string]: string | number }; timeout?: number; retry?: boolean; } export class XompassHTTPClient { static exec(options: XompassHTTPOptions): Promise<any> { let url = options.url; if (options.routeParams) { for (const param of Object.keys(options.routeParams)) { url = url.replace(`:${param}`, options.routeParams[param] + ''); } } const requestOptions = { method: options.method, url: url, data: options.body, headers: options.headers, timeout: options.timeout || XompassClient.getTimeout(), }; logger.log(requestOptions); if (options.retry) { return new Promise((resolve, reject) => { const op = operation({ retries: 1, minTimeout: 5 * 1000, maxTimeout: requestOptions.timeout || 10000, randomize: true, }); op.attempt(async (currentAttempt: number) => { logger.log('sending request: ', currentAttempt, ' attempt'); try { const response = await axios(requestOptions); resolve(response.data); } catch (e: any) { if (op.retry(e)) { return; } reject(new XompassHTTPError(e.response as any)); } }); }); } return axios(requestOptions) .then((response: AxiosResponse) => { return response.data; }) .catch((e: AxiosError) => { throw new XompassHTTPError(e.response as any); }); } }