@cognigy/rest-api-client
Version:
Cognigy REST-Client
184 lines • 9.38 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isAxiosResponse = exports.isAxiosError = exports.AxiosAdapter = void 0;
/* Node Modules */
const axios_1 = require("axios");
/* Custom Modules */
const errors_1 = require("../shared/errors");
const HttpStatusCode_1 = require("../shared/helper/HttpStatusCode");
const IOAuth2ErrorResponse_1 = require("../authentication/OAuth2/IOAuth2ErrorResponse");
const isRetryAllowed_1 = require("./isRetryAllowed");
const isRetryableStatus_1 = require("./isRetryableStatus");
const exponentialDelay_1 = require("./exponentialDelay");
const retryAfterDelay_1 = require("./retryAfterDelay");
class AxiosAdapter {
constructor(config) {
this.config = config;
}
setConfig(config) {
this.config = config;
}
async request(request, client) {
var _a, _b, _c, _d;
const { maxRetries = (_b = (_a = this.config.maxRetries) !== null && _a !== void 0 ? _a : client.config.maxRetries) !== null && _b !== void 0 ? _b : 3, retryCondition = AxiosAdapter.isNetworkOrIdempotentRequestError, retryDelay = exponentialDelay_1.exponentialDelay, shouldResetTimeout = false } = request;
if (request.withAuthentication) {
const authenticationHeaders = await ((_c = client.authenticationHandler) === null || _c === void 0 ? void 0 : _c.getAuthenticationHeaders());
request.headers = Object.assign(Object.assign({}, request.headers), authenticationHeaders);
}
const axiosRequest = await this.convertRequest(request, client);
request.lastRequestTime = Date.now();
request.retryCount = request.retryCount || 0;
if (request.retryCount === maxRetries) {
axiosRequest.validateStatus = null;
}
let axiosResponse;
try {
axiosResponse = await (0, axios_1.default)(axiosRequest);
}
catch (error) {
if (isAxiosError(error)) {
const shouldRetry = retryCondition(error) && request.retryCount < maxRetries;
if (shouldRetry) {
request.retryCount += 1;
const delay = (0, retryAfterDelay_1.retryAfterDelay)((_d = error.response) === null || _d === void 0 ? void 0 : _d.headers, request.lastRequestTime) || retryDelay(request.retryCount, error);
if (!shouldResetTimeout &&
request.timeout &&
request.lastRequestTime) {
const lastRequestDuration = Date.now() - request.lastRequestTime;
request.timeout = Math.max(request.timeout - lastRequestDuration - delay, 1);
}
const requestPromise = new Promise((resolve) => setTimeout(() => resolve(this.request(request, client)), delay));
const response = await requestPromise;
return response;
}
}
this.handleError(error);
}
if (isAxiosError(axiosResponse) || axiosResponse.status >= 400) {
this.handleError(axiosResponse);
}
const response = await this.convertResponse(axiosResponse);
return response;
}
async get(request, client) {
return this.request(Object.assign(Object.assign({}, request), { method: "GET" }), client);
}
async post(request, client) {
return this.request(Object.assign(Object.assign({}, request), { method: "POST" }), client);
}
async patch(request, client) {
return this.request(Object.assign(Object.assign({}, request), { method: "PATCH" }), client);
}
async put(request, client) {
return this.request(Object.assign(Object.assign({}, request), { method: "PUT" }), client);
}
async head(request, client) {
return this.request(Object.assign(Object.assign({}, request), { method: "HEAD" }), client);
}
async convertRequest(request, client) {
var _a, _b;
const baseUrl = (_a = request.baseUrl) !== null && _a !== void 0 ? _a : this.config.baseUrl;
const axiosRequest = {
data: request.data,
headers: request.headers,
method: request.method || "GET",
url: `${baseUrl}${request.url}`,
withCredentials: (_b = request.withCredentials) !== null && _b !== void 0 ? _b : false,
validateStatus: (status) => !(0, isRetryableStatus_1.isRetryableStatus)(status)
};
if (typeof request.onProgress === "function") {
axiosRequest.onDownloadProgress = (progressEvent) => {
const { loaded, total } = progressEvent;
return request.onProgress({ loaded, total });
};
axiosRequest.onUploadProgress = (progressEvent) => {
const { loaded, total } = progressEvent;
return request.onProgress({ loaded, total });
};
}
return axiosRequest;
}
handleError(axiosResponse) {
var _a, _b, _c, _d;
if (isAxiosError(axiosResponse)) {
if (AxiosAdapter.isNetworkError(axiosResponse)) {
throw new errors_1.NetworkError("Request failed. Please check your Network Connection or Firewall Settings.", null, axiosResponse, axiosResponse);
}
else {
const data = ((_a = axiosResponse.response) === null || _a === void 0 ? void 0 : _a.data) || {
code: 500,
detail: "An unexpected error occurred. Please try again later.",
details: {},
traceId: "aixos-error-trace-id"
};
const errorClass = errors_1.ErrorCollection[data.code] ||
errors_1.ErrorCollection[errors_1.ErrorCode.INTERNAL_SERVER_ERROR];
throw new errorClass(data.detail, { traceId: data.traceId }, undefined, data.details);
}
}
if (isAxiosResponse(axiosResponse)) {
let errorClass = errors_1.ErrorCollection[(_b = axiosResponse.data) === null || _b === void 0 ? void 0 : _b.code] ||
errors_1.ErrorCollection[axiosResponse.status] ||
errors_1.ErrorCollection[errors_1.ErrorCode.INTERNAL_SERVER_ERROR];
if ((axiosResponse.status === HttpStatusCode_1.HttpStatusCode.UNAUTHORIZED ||
errorClass === errors_1.ErrorCollection[errors_1.ErrorCode.UNAUTHORIZED_ERROR] ||
IOAuth2ErrorResponse_1.OAuth2Errors.includes((_c = axiosResponse.data) === null || _c === void 0 ? void 0 : _c.error)) &&
typeof this.config.onUnauthorized === "function") {
this.config.onUnauthorized();
}
if (axiosResponse.status === HttpStatusCode_1.HttpStatusCode.CONFLICT) {
errorClass = errors_1.ErrorCollection[errors_1.ErrorCode.CONFLICT_ERROR];
}
if (IOAuth2ErrorResponse_1.OAuth2Errors.includes((_d = axiosResponse.data) === null || _d === void 0 ? void 0 : _d.error)) {
throw new errorClass(axiosResponse.data.detail, { traceId: axiosResponse.data.traceId }, undefined, axiosResponse.data);
}
throw new errorClass(axiosResponse.data.detail, { traceId: axiosResponse.data.traceId }, undefined, axiosResponse.data.details);
}
}
async convertResponse(axiosResponse) {
const response = {
data: axiosResponse.data,
headers: axiosResponse.headers,
status: axiosResponse.status,
statusText: axiosResponse.statusText
};
return response;
}
static isNetworkError(error) {
return (
// https://github.com/softonic/axios-retry/issues/138
(error.isAxiosError && error.message === "Network Error") ||
(!error.response &&
Boolean(error.code) && // Prevents retrying cancelled requests
error.code !== "ECONNABORTED" && // Prevents retrying timed out requests
(0, isRetryAllowed_1.isRetryAllowed)(error.code)) // Prevents retrying unsafe errors
);
}
static isRetryableError(error) {
return (error.code !== "ECONNABORTED" &&
(!error.response || (0, isRetryableStatus_1.isRetryableStatus)(error.response.status)));
}
static isIdempotentRequestError(error) {
if (!error.config) {
// Cannot determine if the request can be retried
return false;
}
return (AxiosAdapter.isRetryableError(error) &&
["get", "head", "options", "put", "delete"].indexOf(error.config.method.toLowerCase()) !== -1);
}
static isNetworkOrIdempotentRequestError(error) {
return (AxiosAdapter.isNetworkError(error) ||
AxiosAdapter.isIdempotentRequestError(error));
}
}
exports.AxiosAdapter = AxiosAdapter;
function isAxiosError(error) {
return (error === null || error === void 0 ? void 0 : error.isAxiosError) === true;
}
exports.isAxiosError = isAxiosError;
function isAxiosResponse(error) {
return ((error === null || error === void 0 ? void 0 : error.isAxiosError) === undefined ||
(error === null || error === void 0 ? void 0 : error.isAxiosError) === false);
}
exports.isAxiosResponse = isAxiosResponse;
//# sourceMappingURL=AxiosAdapter.js.map