UNPKG

@sap-cloud-sdk/core

Version:
187 lines • 9.93 kB
"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 __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 (_) 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 }; } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.OpenApiRequestBuilder = void 0; var util_1 = require("@sap-cloud-sdk/util"); var connectivity_1 = require("../connectivity"); var http_client_1 = require("../http-client"); /** * Request builder for OpenAPI requests. * @typeParam ResponseT - Type of the response for the request. */ var OpenApiRequestBuilder = /** @class */ (function () { /** * Create an instance of `OpenApiRequestBuilder`. * @param method - HTTP method of the request to be built. * @param pathPattern - Path for the request containing path parameter references as in the OpenAPI specification. * @param parameters - Query parameters and or body to pass to the request. */ function OpenApiRequestBuilder(method, pathPattern, parameters) { this.method = method; this.pathPattern = pathPattern; this.parameters = parameters; this.customHeaders = {}; this.customRequestConfiguration = {}; this._fetchCsrfToken = true; } OpenApiRequestBuilder.isPlaceholder = function (pathPart) { return /^\{.+\}$/.test(pathPart); }; /** * Add custom headers to the request. If a header field with the given name already exists it is overwritten. * @param headers - Key-value pairs denoting additional custom headers. * @returns The request builder itself, to facilitate method chaining. */ OpenApiRequestBuilder.prototype.addCustomHeaders = function (headers) { var _this = this; Object.entries(headers).forEach(function (_a) { var key = _a[0], value = _a[1]; _this.customHeaders[key.toLowerCase()] = value; }); return this; }; /** * Add custom request configuration to the request. Typically, this is used when specifying response type for downloading files. * If the custom request configuration contains keys in this list [[defaultDisallowedKeys]], they will be removed. * * @param requestConfiguration - Key-value pairs denoting additional custom request configuration options to be set in the request. * @returns The request builder itself, to facilitate method chaining. */ OpenApiRequestBuilder.prototype.addCustomRequestConfiguration = function (requestConfiguration) { var _this = this; Object.entries(requestConfiguration).forEach(function (_a) { var key = _a[0], value = _a[1]; _this.customRequestConfiguration[key] = value; }); return this; }; /** * Skip fetching csrf token for this request, which is typically useful when the csrf token is not required. * @returns The request builder itself, to facilitate method chaining. */ OpenApiRequestBuilder.prototype.skipCsrfTokenFetching = function () { this._fetchCsrfToken = false; return this; }; /** * Execute request and get a raw HttpResponse, including all information about the HTTP response. * This especially comes in handy, when you need to access the headers or status code of the response. * @param destination - Destination to execute the request against. * @param destinationOptions - Options to employ when fetching destinations. * @returns A promise resolving to an HttpResponse. */ OpenApiRequestBuilder.prototype.executeRaw = function (destination, destinationOptions) { var _a, _b; return __awaiter(this, void 0, void 0, function () { var fetchCsrfToken, resolvedDestination; return __generator(this, function (_c) { switch (_c.label) { case 0: fetchCsrfToken = this._fetchCsrfToken && ['post', 'put', 'patch', 'delete'].includes(this.method.toLowerCase()); return [4 /*yield*/, (0, connectivity_1.useOrFetchDestination)(destination, destinationOptions)]; case 1: resolvedDestination = _c.sent(); if ((0, util_1.isNullish)(destination)) { throw Error((0, connectivity_1.noDestinationErrorMessage)(destination)); } return [2 /*return*/, (0, http_client_1.executeHttpRequest)(resolvedDestination, __assign(__assign({}, (0, http_client_1.filterCustomRequestConfig)(this.customRequestConfiguration)), { method: this.method, url: this.getPath(), headers: this.customHeaders, params: (_a = this.parameters) === null || _a === void 0 ? void 0 : _a.queryParameters, data: (_b = this.parameters) === null || _b === void 0 ? void 0 : _b.body }), // TODO: Remove this in v 2.0, when this becomes true becomes the default { fetchCsrfToken: fetchCsrfToken })]; } }); }); }; /** * Execute request and get the response data. Use this to conveniently access the data of a service without technical information about the response. * @param destination - Destination to execute the request against. * @param destinationOptions - Options to employ when fetching destinations. * @returns A promise resolving to the requested return type. */ OpenApiRequestBuilder.prototype.execute = function (destination, destinationOptions) { return __awaiter(this, void 0, void 0, function () { var response; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.executeRaw(destination, destinationOptions)]; case 1: response = _a.sent(); if (isAxiosResponse(response)) { return [2 /*return*/, response.data]; } throw new Error('Could not access response data. Response was not an axios response.'); } }); }); }; OpenApiRequestBuilder.prototype.getPath = function () { var _a; var pathParameters = ((_a = this.parameters) === null || _a === void 0 ? void 0 : _a.pathParameters) || {}; var pathParts = this.pathPattern.split('/'); return pathParts .map(function (part) { if (OpenApiRequestBuilder.isPlaceholder(part)) { var paramName = part.slice(1, -1); var paramValue = pathParameters[paramName]; if (!paramValue) { throw new Error("Cannot execute request, no path parameter provided for '".concat(paramName, "'.")); } return encodeURIComponent(paramValue); } return part; }) .join('/'); }; return OpenApiRequestBuilder; }()); exports.OpenApiRequestBuilder = OpenApiRequestBuilder; function isAxiosResponse(val) { return 'data' in val; } //# sourceMappingURL=openapi-request-builder.js.map