UNPKG

@nahkies/typescript-axios-runtime

Version:

Runtime package for code generated by @nahkies/openapi-code-generator using the typescript-axios template

98 lines 3.38 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AbstractAxiosClient = void 0; const tslib_1 = require("tslib"); const axios_1 = tslib_1.__importStar(require("axios")); const qs_1 = tslib_1.__importDefault(require("qs")); const url_search_params_1 = require("./request-bodies/url-search-params"); class AbstractAxiosClient { axios; basePath; defaultHeaders; defaultTimeout; constructor(config) { this.axios = config.axios ?? axios_1.default; this.basePath = config.basePath; this.defaultHeaders = config.defaultHeaders ?? {}; this.defaultTimeout = config.defaultTimeout; } _request(opts) { const headers = opts.headers ?? this._headers(); return this.axios.request({ baseURL: this.basePath, ...opts, headers, }); } _query(params) { const definedParams = Object.entries(params).filter(([, v]) => v !== undefined); if (!definedParams.length) { return ""; } return `?${qs_1.default.stringify(Object.fromEntries(definedParams), { indices: false, })}`; } /** * Combines headers for a request, with precedence * 1. default headers * 2. route level header parameters * 3. raw request config (escape hatch) * * following these rules: * - header values of `undefined` are skipped * - header values of `null` will remove/delete any previously set headers * * Eg: * Passing `Authorization: null` as a parameter, will clear out any * default `Authorization` header. * * But passing `Authorization: undefined` as parameter will fallthrough * to the default `Authorization` header. * * @param paramHeaders * @param optsHeaders * @protected */ _headers(paramHeaders = {}, optsHeaders = {}) { const headers = new axios_1.AxiosHeaders(); // axios doesn't know how to append headers, so we just apply // from the lowest priority to highest. this.setHeaders(headers, this.defaultHeaders); this.setHeaders(headers, paramHeaders); this.setHeaders(headers, optsHeaders); return headers; } _requestBodyToUrlSearchParams(obj, encoding = {}) { return (0, url_search_params_1.requestBodyToUrlSearchParams)(obj, encoding); } setHeaders(headers, headersInit) { const headersArray = this.headersAsArray(headersInit); for (const [headerName, headerValue] of headersArray) { if (headerValue === null) { headers.delete(headerName); } else if (headerValue !== undefined) { headers.set(headerName.toLowerCase(), headerValue.toString()); } } } headersAsArray(headers) { if (Array.isArray(headers)) { return headers; } if (headers instanceof Headers) { const result = []; headers.forEach((value, key) => { result.push([key, value]); }); return result; } if (headers && typeof headers === "object") { return Object.entries(headers); } return []; } } exports.AbstractAxiosClient = AbstractAxiosClient; //# sourceMappingURL=main.js.map