UNPKG

11 kBJavaScriptView Raw
1"use strict";
2var __assign = (this && this.__assign) || function () {
3 __assign = Object.assign || function(t) {
4 for (var s, i = 1, n = arguments.length; i < n; i++) {
5 s = arguments[i];
6 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7 t[p] = s[p];
8 }
9 return t;
10 };
11 return __assign.apply(this, arguments);
12};
13var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15 return new (P || (P = Promise))(function (resolve, reject) {
16 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19 step((generator = generator.apply(thisArg, _arguments || [])).next());
20 });
21};
22var __generator = (this && this.__generator) || function (thisArg, body) {
23 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25 function verb(n) { return function (v) { return step([n, v]); }; }
26 function step(op) {
27 if (f) throw new TypeError("Generator is already executing.");
28 while (_) try {
29 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;
30 if (y = 0, t) op = [op[0] & 2, t.value];
31 switch (op[0]) {
32 case 0: case 1: t = op; break;
33 case 4: _.label++; return { value: op[1], done: false };
34 case 5: _.label++; y = op[1]; op = [0]; continue;
35 case 7: op = _.ops.pop(); _.trys.pop(); continue;
36 default:
37 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41 if (t[2]) _.ops.pop();
42 _.trys.pop(); continue;
43 }
44 op = body.call(thisArg, _);
45 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47 }
48};
49var __importDefault = (this && this.__importDefault) || function (mod) {
50 return (mod && mod.__esModule) ? mod : { "default": mod };
51};
52Object.defineProperty(exports, "__esModule", { value: true });
53exports.fetchDestination = exports.fetchSubaccountDestinations = exports.fetchInstanceDestinations = void 0;
54var util_1 = require("@sap-cloud-sdk/util");
55var opossum_1 = __importDefault(require("opossum"));
56var axios_1 = __importDefault(require("axios"));
57var jwt_1 = require("../jwt");
58var resilience_options_1 = require("../resilience-options");
59var http_agent_1 = require("../../../http-agent");
60var destination_1 = require("./destination");
61var destination_service_types_1 = require("./destination-service-types");
62var destination_service_cache_1 = require("./destination-service-cache");
63var logger = util_1.createLogger({
64 package: 'core',
65 messageContext: 'destination-service'
66});
67var circuitBreaker;
68/**
69 * Fetches all instance destinations from the given URI.
70 * @param destinationServiceUri - The URI of the destination service
71 * @param jwt - The access token
72 * @param options - Options to use by retrieving destinations
73 * @returns A promise resolving to a list of instance destinations
74 */
75function fetchInstanceDestinations(destinationServiceUri, jwt, options) {
76 return fetchDestinations(destinationServiceUri, jwt, destination_service_types_1.DestinationType.Instance, options);
77}
78exports.fetchInstanceDestinations = fetchInstanceDestinations;
79/**
80 * Fetches all subaccount destinations from the given URI.
81 * @param destinationServiceUri - The URI of the destination service
82 * @param jwt - The access token
83 * @param options - Options to use by retrieving destinations
84 * @returns A promise resolving to a list of subaccount destinations
85 */
86function fetchSubaccountDestinations(destinationServiceUri, jwt, options) {
87 return fetchDestinations(destinationServiceUri, jwt, destination_service_types_1.DestinationType.Subaccount, options);
88}
89exports.fetchSubaccountDestinations = fetchSubaccountDestinations;
90function fetchDestinations(destinationServiceUri, jwt, type, options) {
91 return __awaiter(this, void 0, void 0, function () {
92 var targetUri, destinationsFromCache, headers;
93 return __generator(this, function (_a) {
94 targetUri = destinationServiceUri.replace(/\/$/, '') + "/destination-configuration/v1/" + type + "Destinations";
95 if (options === null || options === void 0 ? void 0 : options.useCache) {
96 destinationsFromCache = destination_service_cache_1.destinationServiceCache.retrieveDestinationsFromCache(targetUri, jwt_1.decodeJwt(jwt), options.isolationStrategy);
97 if (destinationsFromCache) {
98 return [2 /*return*/, destinationsFromCache];
99 }
100 }
101 headers = jwt_1.wrapJwtInHeader(jwt).headers;
102 return [2 /*return*/, callDestinationService(targetUri, headers, options)
103 .then(function (response) {
104 var destinations = response.data.map(function (d) {
105 return destination_1.parseDestination(d);
106 });
107 if (options === null || options === void 0 ? void 0 : options.useCache) {
108 destination_service_cache_1.destinationServiceCache.cacheRetrievedDestinations(targetUri, jwt_1.decodeJwt(jwt), destinations, options.isolationStrategy);
109 }
110 return destinations;
111 })
112 .catch(function (error) {
113 throw new util_1.ErrorWithCause("Failed to fetch " + type + " destinations." + errorMessageFromResponse(error), error);
114 })];
115 });
116 });
117}
118/**
119 * Fetches a specific destination by name from the given URI, including authorization tokens.
120 * For destinations with authenticationType OAuth2SAMLBearerAssertion, this call will trigger the OAuth2SAMLBearerFlow against the target destination.
121 * In this pass the access token as string.
122 * Fetches a specific destination with authenticationType OAuth2UserTokenExchange by name from the given URI, including authorization tokens.
123 * @param destinationServiceUri - The URI of the destination service
124 * @param token - The access token or AuthAndExchangeTokens if you want to include the X-user-token for OAuth2UserTokenExchange.
125 * @param destinationName - The name of the desired destination
126 * @param options - Options to use by retrieving destinations
127 * @returns A Promise resolving to the destination
128 */
129function fetchDestination(destinationServiceUri, token, destinationName, options) {
130 return __awaiter(this, void 0, void 0, function () {
131 return __generator(this, function (_a) {
132 return [2 /*return*/, fetchDestinationByTokens(destinationServiceUri, typeof token === 'string' ? { authHeaderJwt: token } : token, destinationName, options)];
133 });
134 });
135}
136exports.fetchDestination = fetchDestination;
137function fetchDestinationByTokens(destinationServiceUri, tokens, destinationName, options) {
138 return __awaiter(this, void 0, void 0, function () {
139 var targetUri, destinationsFromCache, authHeader;
140 return __generator(this, function (_a) {
141 targetUri = destinationServiceUri.replace(/\/$/, '') + "/destination-configuration/v1/destinations/" + destinationName;
142 if (options === null || options === void 0 ? void 0 : options.useCache) {
143 destinationsFromCache = destination_service_cache_1.destinationServiceCache.retrieveDestinationsFromCache(targetUri, jwt_1.decodeJwt(tokens.authHeaderJwt), options.isolationStrategy);
144 if (destinationsFromCache) {
145 if (destinationsFromCache.length > 1) {
146 logger.warn('More than one destination found in the cache. This should not happen. First element used.');
147 }
148 return [2 /*return*/, destinationsFromCache[0]];
149 }
150 }
151 authHeader = jwt_1.wrapJwtInHeader(tokens.authHeaderJwt).headers;
152 authHeader = tokens.exchangeHeaderJwt
153 ? __assign(__assign({}, authHeader), { 'X-user-token': tokens.exchangeHeaderJwt }) : authHeader;
154 authHeader = tokens.exchangeTenant
155 ? __assign(__assign({}, authHeader), { 'X-tenant': tokens.exchangeTenant }) : authHeader;
156 return [2 /*return*/, callDestinationService(targetUri, authHeader, options)
157 .then(function (response) {
158 var destination = destination_1.parseDestination(response.data);
159 if (options === null || options === void 0 ? void 0 : options.useCache) {
160 destination_service_cache_1.destinationServiceCache.cacheRetrievedDestinations(targetUri, jwt_1.decodeJwt(tokens.authHeaderJwt), [destination], options.isolationStrategy);
161 }
162 return destination;
163 })
164 .catch(function (error) {
165 {
166 throw new util_1.ErrorWithCause("Failed to fetch destination " + destinationName + "." + errorMessageFromResponse(error), error);
167 }
168 })];
169 });
170 });
171}
172function errorMessageFromResponse(error) {
173 return util_1.propertyExists(error, 'response', 'data', 'ErrorMessage')
174 ? " " + error.response.data.ErrorMessage
175 : '';
176}
177function callDestinationService(uri, headers, options) {
178 if (options === void 0) { options = { enableCircuitBreaker: true }; }
179 var config = __assign(__assign({}, http_agent_1.urlAndAgent(uri)), { proxy: false, method: 'get', headers: headers });
180 if (options.enableCircuitBreaker) {
181 return getCircuitBreaker().fire(config);
182 }
183 return axios_1.default.request(config);
184}
185function getCircuitBreaker() {
186 if (!circuitBreaker) {
187 circuitBreaker = new opossum_1.default(axios_1.default.request, resilience_options_1.circuitBreakerDefaultOptions);
188 }
189 return circuitBreaker;
190}
191//# sourceMappingURL=destination-service.js.map
\No newline at end of file