openapi-client-axios
Version:
JavaScript client library for consuming OpenAPI-enabled APIs with axios. Types included.
731 lines • 34.9 kB
JavaScript
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OpenAPIClientAxios = void 0;
var axios_1 = __importDefault(require("axios"));
var bath_es5_1 = __importDefault(require("bath-es5"));
var dereference_json_schema_1 = require("dereference-json-schema");
var client_1 = require("./types/client");
var DefaultRunnerKey = 'default';
/**
* Main class and the default export of the 'openapi-client-axios' module
*
* @export
* @class OpenAPIClientAxios
*/
var OpenAPIClientAxios = /** @class */ (function () {
/**
* Creates an instance of OpenAPIClientAxios.
*
* @param opts - constructor options
* @param {Document | string} opts.definition - the OpenAPI definition, file path or Document object
* @param {boolean} opts.quick - quick mode, skips validation and doesn't guarantee document is unchanged
* @param {boolean} opts.applyMethodCommonHeaders Should method (patch / post / put / etc.) specific default headers (from axios.defaults.headers.{method}) be applied to operation methods?
* @param {boolean} opts.axiosConfigDefaults - default axios config for the instance
* @memberof OpenAPIClientAxios
*/
function OpenAPIClientAxios(opts) {
var _a;
var _this = this;
/**
* Returns the instance of OpenAPIClient
*
* @returns
* @memberof OpenAPIClientAxios
*/
this.getClient = function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
if (!this.initialized) {
return [2 /*return*/, this.init()];
}
return [2 /*return*/, this.instance];
});
}); };
/**
* Initializes OpenAPIClientAxios and creates a member axios client instance
*
* The init() method should be called right after creating a new instance of OpenAPIClientAxios
*
* @returns AxiosInstance
* @memberof OpenAPIClientAxios
*/
this.init = function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.loadDocument()];
case 1:
_a.sent();
// dereference the document into definition
this.definition = (0, dereference_json_schema_1.dereferenceSync)(this.document);
// create axios instance
this.instance = this.createAxiosInstance();
// we are now initialized
this.initialized = true;
return [2 /*return*/, this.instance];
}
});
}); };
/**
* Synchronous version of .init()
*
* Note: Only works when the input definition is a valid OpenAPI v3 object (URLs are not supported)
*
* @memberof OpenAPIClientAxios
*/
this.initSync = function () {
if (typeof _this.inputDocument !== 'object') {
throw new Error(".initSync() can't be called with a non-object definition. Please use .init()");
}
// set document
_this.document = _this.inputDocument;
// dereference the document into definition
_this.definition = (0, dereference_json_schema_1.dereferenceSync)(_this.document);
// create axios instance
_this.instance = _this.createAxiosInstance();
// we are now initialized
_this.initialized = true;
return _this.instance;
};
/**
* Creates a new axios instance with defaults and returns it
*/
this.getAxiosInstance = function () {
var instance = axios_1.default.create(_this.axiosConfigDefaults);
return instance;
};
/**
* Creates a new axios instance, extends it and returns it
*
* @memberof OpenAPIClientAxios
*/
this.createAxiosInstance = function () {
var e_1, _a;
// create axios instance
var instance = _this.getAxiosInstance();
// set baseURL to the one found in the definition servers (if not set in axios defaults)
var baseURL = _this.getBaseURL();
if (baseURL && !_this.axiosConfigDefaults.baseURL) {
instance.defaults.baseURL = baseURL;
}
// create methods for operationIds
var operations = _this.getOperations();
try {
for (var operations_1 = __values(operations), operations_1_1 = operations_1.next(); !operations_1_1.done; operations_1_1 = operations_1.next()) {
var operation = operations_1_1.value;
var operationId = operation.operationId;
if (operationId) {
instance[_this.transformOperationName(operationId)] = _this.createOperationMethod(operation);
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (operations_1_1 && !operations_1_1.done && (_a = operations_1.return)) _a.call(operations_1);
}
finally { if (e_1) throw e_1.error; }
}
// create paths dictionary
// Example: api.paths['/pets/{id}'].get({ id: 1 });
instance.paths = {};
var _loop_1 = function (path) {
if (_this.definition.paths[path]) {
if (!instance.paths[path]) {
instance.paths[path] = {};
}
var methods = _this.definition.paths[path];
var _loop_2 = function (m) {
if (methods[m] && Object.values(client_1.HttpMethod).includes(m)) {
var method_1 = m;
var operation = _this.getOperations().find(function (op) { return op.method === method_1 && op.path === path; });
instance.paths[path][method_1] = _this.createOperationMethod(operation);
}
};
for (var m in methods) {
_loop_2(m);
}
}
};
for (var path in _this.definition.paths) {
_loop_1(path);
}
// add reference to parent class instance
instance.api = _this;
return instance;
};
/**
* Gets the API baseurl defined in the first OpenAPI specification servers property
*
* @returns string
* @memberof OpenAPIClientAxios
*/
this.getBaseURL = function (operation) {
var e_2, _a, e_3, _b;
if (!_this.definition) {
return undefined;
}
if (operation) {
if (typeof operation === 'string') {
operation = _this.getOperation(operation);
}
if (operation.servers && operation.servers[0]) {
return operation.servers[0].url;
}
}
// get the target server from this.defaultServer
var targetServer;
if (typeof _this.defaultServer === 'number') {
if (_this.definition.servers && _this.definition.servers[_this.defaultServer]) {
targetServer = _this.definition.servers[_this.defaultServer];
}
}
else if (typeof _this.defaultServer === 'string') {
try {
for (var _c = __values(_this.definition.servers), _d = _c.next(); !_d.done; _d = _c.next()) {
var server = _d.value;
if (server.description === _this.defaultServer) {
targetServer = server;
break;
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_2) throw e_2.error; }
}
}
else if (_this.defaultServer.url) {
targetServer = _this.defaultServer;
}
// if no targetServer is found, return undefined
if (!targetServer) {
return undefined;
}
var baseURL = targetServer.url;
var baseURLVariableSet = targetServer.variables;
// get baseURL var names
var baseURLBuilder = (0, bath_es5_1.default)(baseURL);
// if there are no variables to resolve: return baseURL as is
if (!baseURLBuilder.names.length) {
return baseURL;
}
// object to place variables resolved from this.baseURLVariables
var baseURLVariablesResolved = {};
try {
// step through names and assign value from this.baseURLVariables or the default value
// note: any variables defined in baseURLVariables but not actually variables in baseURL are ignored
for (var _e = __values(baseURLBuilder.names), _f = _e.next(); !_f.done; _f = _e.next()) {
var name_1 = _f.value;
var varValue = _this.baseURLVariables[name_1];
if (varValue !== undefined && baseURLVariableSet[name_1].enum) {
// if varValue exists assign to baseURLVariablesResolved object
if (typeof varValue === 'number') {
// if number, get value from enum array
var enumVal = baseURLVariableSet[name_1].enum[varValue];
if (enumVal) {
baseURLVariablesResolved[name_1] = enumVal;
}
else {
// if supplied value out of range: throw error
throw new Error("index ".concat(varValue, " out of range for enum of baseURL variable: ").concat(name_1, "; enum max index is ").concat(baseURLVariableSet[name_1].enum.length - 1));
}
}
else if (typeof varValue === 'string') {
// if string, validate against enum array
if (baseURLVariableSet[name_1].enum.includes(varValue)) {
baseURLVariablesResolved[name_1] = varValue;
}
else {
// if supplied value doesn't exist on enum: throw error
throw new Error("".concat(varValue, " is not a valid entry for baseURL variable ").concat(name_1, "; variable must be of the following: ").concat(baseURLVariableSet[name_1].enum.join(', ')));
}
}
}
else {
// if varValue doesn't exist: get default
baseURLVariablesResolved[name_1] = baseURLVariableSet[name_1].default;
}
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
}
finally { if (e_3) throw e_3.error; }
}
// return resolved baseURL
return baseURLBuilder.path(baseURLVariablesResolved);
};
/**
* Creates an axios config object for operation + arguments
* @memberof OpenAPIClientAxios
*/
this.getAxiosConfigForOperation = function (operation, args) {
if (typeof operation === 'string') {
operation = _this.getOperation(operation);
}
var request = _this.getRequestConfigForOperation(operation, args);
// construct axios request config
var axiosConfig = {
method: request.method,
url: request.path,
data: request.payload,
params: request.query,
headers: request.headers,
};
// allow overriding baseURL with operation / path specific servers
var servers = operation.servers;
if (servers && servers[0]) {
axiosConfig.baseURL = servers[0].url;
}
// allow overriding any parameters in AxiosRequestConfig
var _a = __read(args, 3), config = _a[2];
return __assign(__assign(__assign({}, axiosConfig), config), { params: __assign(__assign({}, axiosConfig === null || axiosConfig === void 0 ? void 0 : axiosConfig.params), config === null || config === void 0 ? void 0 : config.params), headers: __assign(__assign({}, axiosConfig === null || axiosConfig === void 0 ? void 0 : axiosConfig.headers), config === null || config === void 0 ? void 0 : config.headers) });
};
/**
* Creates a generic request config object for operation + arguments.
*
* This function contains the logic that handles operation method parameters.
*
* @memberof OpenAPIClientAxios
*/
this.getRequestConfigForOperation = function (operation, args) {
var e_4, _a, e_5, _b, e_6, _c, e_7, _d;
var _e, _f;
if (typeof operation === 'string') {
operation = _this.getOperation(operation);
}
var pathParams = {};
var searchParams = new URLSearchParams();
var query = {};
var headers = {};
var cookies = {};
var parameters = (operation.parameters || []);
var setRequestParam = function (name, value, type) {
var e_8, _a;
switch (type) {
case client_1.ParamType.Path:
pathParams[name] = value;
break;
case client_1.ParamType.Query:
if (Array.isArray(value)) {
try {
for (var value_1 = __values(value), value_1_1 = value_1.next(); !value_1_1.done; value_1_1 = value_1.next()) {
var valueItem = value_1_1.value;
searchParams.append(name, valueItem);
}
}
catch (e_8_1) { e_8 = { error: e_8_1 }; }
finally {
try {
if (value_1_1 && !value_1_1.done && (_a = value_1.return)) _a.call(value_1);
}
finally { if (e_8) throw e_8.error; }
}
}
else {
searchParams.append(name, value);
}
query[name] = value;
break;
case client_1.ParamType.Header:
headers[name] = value;
break;
case client_1.ParamType.Cookie:
cookies[name] = value;
break;
}
};
var getParamType = function (paramName) {
var param = parameters.find(function (_a) {
var name = _a.name;
return name === paramName;
});
if (param) {
return param.in;
}
// default all params to query if operation doesn't specify param
return client_1.ParamType.Query;
};
var getFirstOperationParam = function () {
var firstRequiredParam = parameters.find(function (_a) {
var required = _a.required;
return required === true;
});
if (firstRequiredParam) {
return firstRequiredParam;
}
var firstParam = parameters[0];
if (firstParam) {
return firstParam;
}
};
var _g = __read(args, 2), paramsArg = _g[0], payload = _g[1];
if (Array.isArray(paramsArg)) {
try {
// ParamsArray
for (var paramsArg_1 = __values(paramsArg), paramsArg_1_1 = paramsArg_1.next(); !paramsArg_1_1.done; paramsArg_1_1 = paramsArg_1.next()) {
var param = paramsArg_1_1.value;
setRequestParam(param.name, param.value, param.in || getParamType(param.name));
}
}
catch (e_4_1) { e_4 = { error: e_4_1 }; }
finally {
try {
if (paramsArg_1_1 && !paramsArg_1_1.done && (_a = paramsArg_1.return)) _a.call(paramsArg_1);
}
finally { if (e_4) throw e_4.error; }
}
}
else if (typeof paramsArg === 'object') {
// ParamsObject
for (var name_2 in paramsArg) {
if (paramsArg[name_2] !== undefined) {
setRequestParam(name_2, paramsArg[name_2], getParamType(name_2));
}
}
}
else if (paramsArg) {
var firstParam = getFirstOperationParam();
if (!firstParam) {
throw new Error("No parameters found for operation ".concat(operation.operationId));
}
setRequestParam(firstParam.name, paramsArg, firstParam.in);
}
// path parameters
var pathBuilder = (0, bath_es5_1.default)(operation.path);
try {
// make sure all path parameters are set
for (var _h = __values(pathBuilder.names), _j = _h.next(); !_j.done; _j = _h.next()) {
var name_3 = _j.value;
var value = pathParams[name_3];
pathParams[name_3] = "".concat(value);
}
}
catch (e_5_1) { e_5 = { error: e_5_1 }; }
finally {
try {
if (_j && !_j.done && (_b = _h.return)) _b.call(_h);
}
finally { if (e_5) throw e_5.error; }
}
var path = pathBuilder.path(pathParams);
// queryString parameter
var queryString = searchParams.toString();
// full url with query string
var url = "".concat(_this.getBaseURL(operation)).concat(path).concat(queryString ? "?".concat(queryString) : '');
// add default common headers
var defaultHeaders = _this.client.defaults.headers;
try {
for (var _k = __values(Object.entries((_e = defaultHeaders.common) !== null && _e !== void 0 ? _e : {})), _l = _k.next(); !_l.done; _l = _k.next()) {
var _m = __read(_l.value, 2), key = _m[0], val = _m[1];
headers[key] = val;
}
}
catch (e_6_1) { e_6 = { error: e_6_1 }; }
finally {
try {
if (_l && !_l.done && (_c = _k.return)) _c.call(_k);
}
finally { if (e_6) throw e_6.error; }
}
// add method specific default headers
if (_this.applyMethodCommonHeaders) {
var methodHeaders = (_f = defaultHeaders[operation.method]) !== null && _f !== void 0 ? _f : {};
try {
for (var _o = __values(Object.entries(methodHeaders)), _p = _o.next(); !_p.done; _p = _o.next()) {
var _q = __read(_p.value, 2), key = _q[0], val = _q[1];
headers[key] = val;
}
}
catch (e_7_1) { e_7 = { error: e_7_1 }; }
finally {
try {
if (_p && !_p.done && (_d = _o.return)) _d.call(_o);
}
finally { if (e_7) throw e_7.error; }
}
}
// construct request config
var config = {
method: operation.method,
url: url,
path: path,
pathParams: pathParams,
query: query,
queryString: queryString,
headers: headers,
cookies: cookies,
payload: payload,
};
return config;
};
/**
* Flattens operations into a simple array of Operation objects easy to work with
*
* @returns {Operation[]}
* @memberof OpenAPIBackend
*/
this.getOperations = function () {
var _a;
var paths = ((_a = _this.definition) === null || _a === void 0 ? void 0 : _a.paths) || {};
return Object.entries(paths).flatMap(function (_a) {
var _b = __read(_a, 2), path = _b[0], pathObject = _b[1];
return Object.values(client_1.HttpMethod)
.map(function (method) { return ({ path: path, method: method, operation: pathObject[method] }); })
.filter(function (_a) {
var operation = _a.operation;
return operation;
})
.map(function (_a) {
var _b;
var operation = _a.operation, method = _a.method;
var op = __assign(__assign({}, (typeof operation === 'object' ? operation : {})), { path: path, method: method });
if (pathObject.parameters) {
op.parameters = __spreadArray(__spreadArray([], __read((op.parameters || [])), false), __read(pathObject.parameters), false);
}
if (pathObject.servers) {
op.servers = __spreadArray(__spreadArray([], __read((op.servers || [])), false), __read(pathObject.servers), false);
}
op.security = (_b = op.security) !== null && _b !== void 0 ? _b : _this.definition.security;
return op;
});
});
};
/**
* Gets a single operation based on operationId
*
* @param {string} operationId
* @returns {Operation}
* @memberof OpenAPIBackend
*/
this.getOperation = function (operationId) {
return _this.getOperations().find(function (op) { return op.operationId === operationId; });
};
/**
* Creates an axios method for an operation
* (...pathParams, data?, config?) => Promise<AxiosResponse>
*
* @param {Operation} operation
* @memberof OpenAPIClientAxios
*/
this.createOperationMethod = function (operation) {
var originalOperationMethod = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return __awaiter(_this, void 0, void 0, function () {
var axiosConfig, runner;
return __generator(this, function (_a) {
axiosConfig = this.getAxiosConfigForOperation(operation, args);
runner = this.getRunner(operation.operationId);
return [2 /*return*/, runner.runRequest(axiosConfig, operation, runner.context)];
});
});
};
return _this.transformOperationMethod(originalOperationMethod, operation);
};
var optsWithDefaults = __assign(__assign({ quick: false, withServer: 0, baseURLVariables: {}, transformOperationName: function (operationId) { return operationId; }, transformOperationMethod: function (operationMethod) { return operationMethod; }, axiosRunner: function (axiosConfig) { return _this.client.request(axiosConfig); }, applyMethodCommonHeaders: false }, opts), { axiosConfigDefaults: __assign({}, (opts.axiosConfigDefaults || {})) });
this.inputDocument = optsWithDefaults.definition;
this.quick = optsWithDefaults.quick;
this.axiosConfigDefaults = optsWithDefaults.axiosConfigDefaults;
this.defaultServer = optsWithDefaults.withServer;
this.baseURLVariables = optsWithDefaults.baseURLVariables;
this.applyMethodCommonHeaders = optsWithDefaults.applyMethodCommonHeaders;
this.transformOperationName = optsWithDefaults.transformOperationName;
this.transformOperationMethod = optsWithDefaults.transformOperationMethod;
this.runners = (_a = {},
_a[DefaultRunnerKey] = { runRequest: optsWithDefaults.axiosRunner },
_a);
}
Object.defineProperty(OpenAPIClientAxios.prototype, "client", {
/**
* Returns the instance of OpenAPIClient
*
* @readonly
* @type {OpenAPIClient}
* @memberof OpenAPIClientAxios
*/
get: function () {
return this.instance;
},
enumerable: false,
configurable: true
});
OpenAPIClientAxios.prototype.withServer = function (server, variables) {
if (variables === void 0) { variables = {}; }
this.defaultServer = server;
this.baseURLVariables = variables;
};
/**
* Loads document from inputDocument
*
* Supports loading from a string (url) or an object (json)
*
* @memberof OpenAPIClientAxios
*/
OpenAPIClientAxios.prototype.loadDocument = function () {
var _a;
return __awaiter(this, void 0, void 0, function () {
var client, documentRes, yaml, err;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!(typeof this.inputDocument === 'object')) return [3 /*break*/, 1];
this.document = this.inputDocument;
return [3 /*break*/, 6];
case 1:
client = this.getAxiosInstance();
return [4 /*yield*/, client.get(this.inputDocument)];
case 2:
documentRes = _b.sent();
if (!(typeof documentRes.data === 'object')) return [3 /*break*/, 3];
// json response
this.document = documentRes.data;
return [3 /*break*/, 6];
case 3:
if (!(typeof documentRes.data === 'string' && ((_a = documentRes.headers['content-type']) === null || _a === void 0 ? void 0 : _a.match(/ya?ml/)))) return [3 /*break*/, 5];
return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(require('js-yaml')); })];
case 4:
yaml = _b.sent();
this.document = yaml.load(documentRes.data);
return [3 /*break*/, 6];
case 5:
err = new Error("Invalid response fetching OpenAPI definition: ".concat(documentRes));
err.response = documentRes;
throw err;
case 6: return [2 /*return*/, this.document];
}
});
});
};
/**
* By default OpenAPIClient will use axios as request runner. You can register a different runner,
* in case you want to switch over from axios. This allows transitioning from axios to your library of choice.
* @param runner - request runner to be registered, either for all operations, or just one operation.
* @param operationId - optional parameter. If provided, runner will be registered for a single operation. Else, it will be registered for all operations.
*/
OpenAPIClientAxios.prototype.registerRunner = function (runner, operationId) {
this.runners[operationId !== null && operationId !== void 0 ? operationId : DefaultRunnerKey] = runner;
};
OpenAPIClientAxios.prototype.getRunner = function (operationId) {
var _a;
return (_a = this.runners[operationId]) !== null && _a !== void 0 ? _a : this.runners[DefaultRunnerKey];
};
return OpenAPIClientAxios;
}());
exports.OpenAPIClientAxios = OpenAPIClientAxios;
//# sourceMappingURL=client.js.map