@odata2ts/http-client-axios
Version:
Axios based odata HTTP client consumable by odata2ts
61 lines • 3.15 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AxiosClient = exports.DEFAULT_ERROR_MESSAGE = void 0;
const tslib_1 = require("tslib");
const http_client_base_1 = require("@odata2ts/http-client-base");
const axios_1 = tslib_1.__importDefault(require("axios"));
const AxiosClientError_1 = require("./AxiosClientError");
const AxiosRequestConfig_1 = require("./AxiosRequestConfig");
exports.DEFAULT_ERROR_MESSAGE = "No error message!";
const FAILURE_NO_RESPONSE = "No response from server! Failure: ";
const FAILURE_NO_REQUEST = "No request was sent! Failure: ";
const FAILURE_RESPONSE_MESSAGE = "OData server responded with error: ";
const FAILURE_AXIOS = "Fatal Axios failure: ";
function buildErrorMessage(prefix, error) {
const msg = typeof error === "string" ? error : error === null || error === void 0 ? void 0 : error.message;
return prefix + (msg || exports.DEFAULT_ERROR_MESSAGE);
}
class AxiosClient extends http_client_base_1.BaseHttpClient {
constructor(config, clientOptions) {
super(clientOptions);
this.client = axios_1.default.create(config);
}
executeRequest(method, url, data, requestConfig = {}, internalConfig = {}) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
// add URL, HTTP method and additional headers to the request config
const { headers } = internalConfig;
const config = (0, AxiosRequestConfig_1.mergeConfig)({ headers }, requestConfig, { url, method });
if (typeof data !== "undefined") {
config.data = data;
}
if (internalConfig.dataType && internalConfig.dataType !== "json") {
config.responseType = internalConfig.dataType;
}
try {
return yield this.client.request(config);
}
catch (error) {
if (error.isAxiosError) {
const axiosError = error;
// regular failure handling
if (axiosError.response) {
const errMsg = this.retrieveErrorMessage(axiosError.response.data);
const msg = buildErrorMessage(FAILURE_RESPONSE_MESSAGE, errMsg);
throw new AxiosClientError_1.AxiosClientError(msg, axiosError.response.status, this.mapHeaders(axiosError.response.headers), new Error(errMsg || exports.DEFAULT_ERROR_MESSAGE), axiosError);
}
// fatal failure without response
else {
throw new AxiosClientError_1.AxiosClientError(buildErrorMessage(axiosError.request ? FAILURE_NO_RESPONSE : FAILURE_NO_REQUEST, axiosError), undefined, undefined, error, axiosError);
}
}
// not an Axios error
throw new AxiosClientError_1.AxiosClientError(buildErrorMessage(FAILURE_AXIOS, error), undefined, undefined, error);
}
});
}
mapHeaders(headers) {
return headers;
}
}
exports.AxiosClient = AxiosClient;
//# sourceMappingURL=AxiosClient.js.map