@sap-cloud-sdk/core
Version:
SAP Cloud SDK for JavaScript core
291 lines • 14.8 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 __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 };
}
};
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));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ODataRequest = void 0;
var util_1 = require("@sap-cloud-sdk/util");
var connectivity_1 = require("../../connectivity");
var remove_slashes_1 = require("../remove-slashes");
var http_client_1 = require("../../http-client");
var odata_request_traits_1 = require("./odata-request-traits");
/**
* OData request configuration for an entity type.
* @typeparam EntityT - Type of the entity to setup a request for
*/
var ODataRequest = /** @class */ (function () {
/**
* Creates an instance of ODataRequest.
* @param config - Configuration of the request.
* @param _destination - Destination to setup the request against.
*/
function ODataRequest(config, _destination) {
this.config = config;
this._destination = _destination;
}
Object.defineProperty(ODataRequest.prototype, "destination", {
get: function () {
return this._destination;
},
set: function (dest) {
this._destination = dest && (0, connectivity_1.sanitizeDestination)(dest);
},
enumerable: false,
configurable: true
});
/**
* Constructs an absolute URL for the given request.
* @returns The absolute URL for the request.
*/
ODataRequest.prototype.url = function () {
return "".concat((0, remove_slashes_1.removeTrailingSlashes)(this.resourceUrl())).concat(this.config.appendedPaths.join('')).concat(this.query());
};
/**
* Constructs a URL relative to the destination.
* @param includeServicePath - Whether or not to include the service path in the URL.
* @param includeQueryParameters - Whether or not to include the query parameters in the URL.
* @returns The relative URL for the request.
*/
ODataRequest.prototype.relativeUrl = function (includeServicePath, includeQueryParameters) {
if (includeServicePath === void 0) { includeServicePath = true; }
if (includeQueryParameters === void 0) { includeQueryParameters = true; }
var query = includeQueryParameters ? this.query() : '';
return "".concat((0, remove_slashes_1.removeTrailingSlashes)(this.relativeResourceUrl(includeServicePath))).concat(this.config.appendedPaths.join('')).concat(query);
};
/**
* Specifies whether the destination needs a specific authentication or not.
* @returns A boolean value that specifies whether the destination needs authentication or not
*/
ODataRequest.prototype.needsAuthentication = function () {
return (!!this.destination &&
this.destination.authentication !== 'NoAuthentication');
};
/**
* Returns the service URL for a given OData request.
* @returns The URL of the service the given entity belongs to
*/
ODataRequest.prototype.serviceUrl = function () {
if (!this.destination) {
throw Error('The destination is undefined.');
}
var systemUrl = this.destination.url;
var servicePath = typeof this.config.customServicePath === 'undefined'
? this.config.defaultServicePath
: this.config.customServicePath;
return "".concat((0, remove_slashes_1.removeTrailingSlashes)(systemUrl), "/").concat((0, remove_slashes_1.removeSlashes)(servicePath));
};
/**
* Returns the service URL relative to the url of the destination for a given OData request.
* @returns The relative URL of the service the given entity belongs to.
*/
ODataRequest.prototype.relativeServiceUrl = function () {
var servicePath = typeof this.config.customServicePath === 'undefined'
? this.config.defaultServicePath
: this.config.customServicePath;
return "".concat((0, remove_slashes_1.removeSlashes)(servicePath));
};
/**
* Returns the URL to a specific OData .resource, i.e. the entity collection.
* @returns The URL of the resource
*/
ODataRequest.prototype.resourceUrl = function () {
return "".concat((0, remove_slashes_1.removeTrailingSlashes)(this.serviceUrl()), "/").concat(this.config.resourcePath());
};
/**
* Returns the relative URL to a specific OData resource.
* @param includeServicePath - Whether or not to include the service path in the URL.
* @returns The relative URL of the resource.
*/
ODataRequest.prototype.relativeResourceUrl = function (includeServicePath) {
if (includeServicePath === void 0) { includeServicePath = true; }
var baseUrl = includeServicePath
? (0, remove_slashes_1.removeTrailingSlashes)(this.relativeServiceUrl())
: '';
var url = "".concat(baseUrl, "/").concat(this.config.resourcePath());
return (0, remove_slashes_1.removeLeadingSlashes)(url);
};
/**
* Get query parameters as string. Leads with `?` if there are parameters to return.
* @returns Query parameter string
*/
ODataRequest.prototype.query = function () {
var query = Object.entries(this.queryParameters())
.map(function (_a) {
var key = _a[0], value = _a[1];
return "".concat(key, "=").concat(value);
})
.join('&');
return query.length ? "?".concat(query) : '';
};
/**
* Create object containing all headers, including custom headers for the given request.
* @returns Key-value pairs where the key is the name of a header property and the value is the respective value
*/
ODataRequest.prototype.headers = function () {
return __awaiter(this, void 0, void 0, function () {
var destinationRelatedHeaders, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
if (!this.destination) {
throw Error('The destination is undefined.');
}
return [4 /*yield*/, (0, connectivity_1.buildHeadersForDestination)(this.destination, this.config.customHeaders)];
case 1:
destinationRelatedHeaders = _a.sent();
return [2 /*return*/, __assign(__assign(__assign(__assign({}, destinationRelatedHeaders), this.defaultHeaders()), this.eTagHeaders()), this.customHeaders())];
case 2:
error_1 = _a.sent();
throw new util_1.ErrorWithCause('Constructing headers for OData request failed!', error_1);
case 3: return [2 /*return*/];
}
});
});
};
/**
* Get all custom headers.
* @returns Key-value pairs where the key is the name of a header property and the value is the respective value
*/
ODataRequest.prototype.customHeaders = function () {
return this.config.customHeaders;
};
/**
* Get all default headers. If custom headers are set, those take precedence.
* @returns Key-value pairs where the key is the name of a header property and the value is the respective value
*/
ODataRequest.prototype.defaultHeaders = function () {
var additionalHeaders = this.getAdditionalHeadersForKeys.apply(this, Object.keys(this.config.defaultHeaders));
return (0, util_1.mergeIgnoreCase)((0, util_1.pickNonNullish)(this.config.defaultHeaders), additionalHeaders);
};
/**
* Get the eTag related headers, e. g. `if-match`.
* @returns Key-value pairs where the key is the name of a header property and the value is the respective value
*/
ODataRequest.prototype.eTagHeaders = function () {
var additionalIfMatchHeader = this.getAdditionalHeadersForKeys('if-match');
if (Object.keys(additionalIfMatchHeader).length) {
return additionalIfMatchHeader;
}
var eTag = (0, odata_request_traits_1.isWithETag)(this.config)
? this.config.versionIdentifierIgnored
? '*'
: this.config.eTag
: undefined;
return (0, util_1.pickNonNullish)({ 'if-match': eTag });
};
/**
* Execute the given request and return the according promise.
* @returns Promise resolving to the requested data
*/
ODataRequest.prototype.execute = function () {
return __awaiter(this, void 0, void 0, function () {
var destination, _a, _b, _c;
var _d;
var _this = this;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
destination = this.destination;
if (!destination) {
throw Error('The destination cannot be undefined.');
}
_a = http_client_1.executeHttpRequest;
_b = [destination];
_c = [__assign({}, (0, http_client_1.filterCustomRequestConfig)(this.config.customRequestConfiguration))];
_d = {};
return [4 /*yield*/, this.headers()];
case 1: return [2 /*return*/, _a.apply(void 0, _b.concat([__assign.apply(void 0, _c.concat([(_d.headers = _e.sent(), _d.params = this.queryParameters(), _d.url = this.relativeUrl(true, false), _d.method = this.config.method, _d.data = this.config.payload, _d)])), { fetchCsrfToken: this.config.fetchCsrfToken }])).catch(function (error) {
throw constructError(error, _this.config.method, _this.serviceUrl());
})];
}
});
});
};
ODataRequest.prototype.getAdditionalHeadersForKeys = function () {
var _a;
var keys = [];
for (var _i = 0; _i < arguments.length; _i++) {
keys[_i] = arguments[_i];
}
var destinationHeaders = util_1.pickIgnoreCase.apply(void 0, __spreadArray([(_a = this.destination) === null || _a === void 0 ? void 0 : _a.headers], keys, false));
var customHeaders = util_1.pickIgnoreCase.apply(void 0, __spreadArray([this.customHeaders()], keys, false));
return (0, util_1.mergeIgnoreCase)(destinationHeaders, customHeaders);
};
ODataRequest.prototype.queryParameters = function () {
var _a;
return __assign(__assign(__assign({}, this.config.queryParameters()), (_a = this.destination) === null || _a === void 0 ? void 0 : _a.queryParameters), this.config.customQueryParameters);
};
return ODataRequest;
}());
exports.ODataRequest = ODataRequest;
function constructError(error, requestMethod, url) {
if (error.isAxiosError) {
var defaultMessage = "".concat(requestMethod, " request to ").concat(url, " failed!");
var s4SpecificMessage = (0, util_1.propertyExists)(error, 'response', 'data', 'error')
? messageFromS4ErrorResponse(error)
: '';
var message = [defaultMessage, s4SpecificMessage].join(' ');
return new util_1.ErrorWithCause(message, error);
}
return error;
}
function messageFromS4ErrorResponse(error) {
return "".concat((0, util_1.propertyExists)(error.response.data.error, 'message', 'value')
? error.response.data.error.message.value
: '').concat(util_1.unixEOL).concat(JSON.stringify(error.response.data.error));
}
//# sourceMappingURL=odata-request.js.map