UNPKG

@itwin/imodels-client-management

Version:

iModels API client wrapper for applications that manage iModels.

84 lines 3.5 kB
/*--------------------------------------------------------------------------------------------- * Copyright (c) Bentley Systems, Incorporated. All rights reserved. * See LICENSE.md in the project root for license terms and full copyright notice. *--------------------------------------------------------------------------------------------*/ import axios from "axios"; import { UtilityFunctions } from "../internal/"; import { ContentType, } from "../types/RestClient"; import { AxiosResponseHeadersAdapter } from "./AxiosResponseHeadersAdapter"; /** Default implementation for {@link RestClient} interface that uses `axios` library for sending the requests. */ export class AxiosRestClient { static retryCountUpperBound = 10; _retryPolicy; constructor(retryPolicy) { this._retryPolicy = retryPolicy; } async sendGetRequest(params) { const requestConfig = { headers: params.headers, }; if (params.responseType === ContentType.Png) { requestConfig.responseType = "arraybuffer"; const response = await this.executeRequest(async () => axios.get(params.url, requestConfig)); const data = response.body; if (data instanceof ArrayBuffer) return { ...response, body: new Uint8Array(data) }; return response; } return this.executeRequest(async () => axios.get(params.url, requestConfig)); } async sendPostRequest(params) { const requestConfig = { headers: params.headers, }; return this.executeRequest(async () => axios.post(params.url, params.body.content ?? {}, requestConfig)); } async sendPutRequest(params) { const requestConfig = { headers: params.headers, }; return this.executeRequest(async () => axios.put(params.url, params.body?.content, requestConfig)); } async sendPatchRequest(params) { const requestConfig = { headers: params.headers, }; return this.executeRequest(async () => axios.patch(params.url, params.body.content ?? {}, requestConfig)); } async sendDeleteRequest(params) { const requestConfig = { headers: params.headers, }; return this.executeRequest(async () => axios.delete(params.url, requestConfig)); } async executeRequest(requestFunc) { const response = await this.executeWithRetry(requestFunc); return { body: response.data, headers: new AxiosResponseHeadersAdapter(response), }; } async executeWithRetry(requestFunc) { let retriesInvoked = 0; for (;;) { try { return await requestFunc(); } catch (error) { if (this._retryPolicy === null || retriesInvoked >= this._retryPolicy.maxRetries || retriesInvoked >= AxiosRestClient.retryCountUpperBound || !(await this._retryPolicy.shouldRetry({ retriesInvoked, error }))) { throw error; } const sleepDurationInMs = this._retryPolicy.getSleepDurationInMs({ retriesInvoked: retriesInvoked++, }); if (sleepDurationInMs > 0) { await UtilityFunctions.sleep(sleepDurationInMs); } } } } } //# sourceMappingURL=AxiosRestClient.js.map