UNPKG

15.8 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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14 if (k2 === undefined) k2 = k;
15 var desc = Object.getOwnPropertyDescriptor(m, k);
16 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
17 desc = { enumerable: true, get: function() { return m[k]; } };
18 }
19 Object.defineProperty(o, k2, desc);
20}) : (function(o, m, k, k2) {
21 if (k2 === undefined) k2 = k;
22 o[k2] = m[k];
23}));
24var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
25 Object.defineProperty(o, "default", { enumerable: true, value: v });
26}) : function(o, v) {
27 o["default"] = v;
28});
29var __importStar = (this && this.__importStar) || function (mod) {
30 if (mod && mod.__esModule) return mod;
31 var result = {};
32 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
33 __setModuleDefault(result, mod);
34 return result;
35};
36var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
37 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
38 return new (P || (P = Promise))(function (resolve, reject) {
39 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
40 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
41 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
42 step((generator = generator.apply(thisArg, _arguments || [])).next());
43 });
44};
45var __generator = (this && this.__generator) || function (thisArg, body) {
46 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
47 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
48 function verb(n) { return function (v) { return step([n, v]); }; }
49 function step(op) {
50 if (f) throw new TypeError("Generator is already executing.");
51 while (_) try {
52 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;
53 if (y = 0, t) op = [op[0] & 2, t.value];
54 switch (op[0]) {
55 case 0: case 1: t = op; break;
56 case 4: _.label++; return { value: op[1], done: false };
57 case 5: _.label++; y = op[1]; op = [0]; continue;
58 case 7: op = _.ops.pop(); _.trys.pop(); continue;
59 default:
60 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
61 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
62 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
63 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
64 if (t[2]) _.ops.pop();
65 _.trys.pop(); continue;
66 }
67 op = body.call(thisArg, _);
68 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
69 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
70 }
71};
72var __importDefault = (this && this.__importDefault) || function (mod) {
73 return (mod && mod.__esModule) ? mod : { "default": mod };
74};
75Object.defineProperty(exports, "__esModule", { value: true });
76exports.shouldHandleCsrfToken = exports.getAxiosConfigWithDefaultsWithoutMethod = exports.getAxiosConfigWithDefaults = exports.executeHttpRequest = exports.buildAxiosRequestConfig = exports.execute = exports.addDestinationToRequestConfig = exports.buildHttpRequest = void 0;
77var http = __importStar(require("http"));
78var https = __importStar(require("https"));
79var util_1 = require("@sap-cloud-sdk/util");
80var axios_1 = __importDefault(require("axios"));
81var scp_cf_1 = require("../connectivity/scp-cf");
82var http_client_1 = require("../http-client");
83var http_agent_1 = require("../http-agent/http-agent");
84var logger = (0, util_1.createLogger)({
85 package: 'core',
86 messageContext: 'http-client'
87});
88/**
89 * Builds a [[DestinationHttpRequestConfig]] for the given destination.
90 * If a destination name (and a JWT) are provided, it will try to resolve the destination.
91 * @param destination - A destination or a destination name and a JWT.
92 * @param customHeaders - Custom default headers for the resulting HTTP request.
93 * @returns A [[DestinationHttpRequestConfig]].
94 */
95function buildHttpRequest(destination, customHeaders) {
96 return __awaiter(this, void 0, void 0, function () {
97 var resolvedDestination, headers;
98 return __generator(this, function (_a) {
99 switch (_a.label) {
100 case 0:
101 if (customHeaders) {
102 logger.info("The following custom headers will overwrite headers created by the SDK:\n".concat(Object.keys(customHeaders)
103 .map(function (key) { return " - \"".concat(key, "\""); })
104 .join('\n')));
105 }
106 return [4 /*yield*/, resolveDestination(destination)];
107 case 1:
108 resolvedDestination = _a.sent();
109 if (!resolvedDestination) {
110 throw Error("Failed to resolve the destination '".concat((0, scp_cf_1.toDestinationNameUrl)(destination), "'."));
111 }
112 return [4 /*yield*/, buildHeaders(resolvedDestination, customHeaders)];
113 case 2:
114 headers = _a.sent();
115 return [2 /*return*/, buildDestinationHttpRequestConfig(resolvedDestination, headers)];
116 }
117 });
118 });
119}
120exports.buildHttpRequest = buildHttpRequest;
121/**
122 * Builds a [[DestinationHttpRequestConfig]] for the given destination
123 * and then merges it into the given request configuration.
124 * Setting of the given request configuration take precedence over any destination related configuration.
125 * @param destination - A destination or a destination name and a JWT.
126 * @param requestConfig - Any object representing an HTTP request.
127 * @returns The given request config merged with the config built for the given destination.
128 */
129function addDestinationToRequestConfig(destination, requestConfig) {
130 return buildHttpRequest(destination).then(function (destinationConfig) {
131 return merge(destinationConfig, requestConfig);
132 });
133}
134exports.addDestinationToRequestConfig = addDestinationToRequestConfig;
135/**
136 * Takes as parameter a function that expects an [[HttpRequest]] and returns a Promise of [[HttpResponse]].
137 * Returns a function that takes a destination and a request-config (extends [[HttpRequestConfig]]), builds an [[HttpRequest]] from them, and calls
138 * the provided execute function.
139 *
140 * NOTE: If you simply want to execute a request without passing your own execute function, use [[executeHttpRequest]] instead.
141 * @param executeFn - A function that can execute an [[HttpRequestConfig]].
142 * @returns A function expecting destination and a request.
143 */
144function execute(executeFn) {
145 return function (destination, requestConfig, options) {
146 return __awaiter(this, void 0, void 0, function () {
147 var destinationRequestConfig, request, _a;
148 return __generator(this, function (_b) {
149 switch (_b.label) {
150 case 0: return [4 /*yield*/, buildHttpRequest(destination, requestConfig.headers)];
151 case 1:
152 destinationRequestConfig = _b.sent();
153 request = merge(destinationRequestConfig, requestConfig);
154 _a = request;
155 return [4 /*yield*/, addCsrfTokenToHeader(destination, request, options)];
156 case 2:
157 _a.headers = _b.sent();
158 logRequestInformation(request);
159 return [2 /*return*/, executeFn(request)];
160 }
161 });
162 });
163 };
164}
165exports.execute = execute;
166function logRequestInformation(request) {
167 var basicRequestInfo = "Execute '".concat(request.method, "' request with target: ").concat(request.url, ".");
168 var headerText = Object.keys(request.headers).reduce(function (previous, key) {
169 if (key.toLowerCase().includes('authentication') ||
170 key.toLowerCase().includes('authorization')) {
171 return "".concat(previous).concat(util_1.unixEOL).concat(key, ":*******");
172 }
173 return "".concat(previous).concat(util_1.unixEOL).concat(key, ":").concat(request.headers[key]);
174 }, 'The headers of the request are:');
175 logger.debug("".concat(basicRequestInfo).concat(util_1.unixEOL).concat(headerText));
176}
177/**
178 *
179 * @experimental This API is experimental and might change in newer versions. Use with caution.
180 * @param destination - A destination or a destination name and a JWT.
181 * @param requestConfig - Any object representing an HTTP request.
182 */
183function buildAxiosRequestConfig(destination, requestConfig) {
184 return __awaiter(this, void 0, void 0, function () {
185 var destinationRequestConfig, request;
186 return __generator(this, function (_a) {
187 switch (_a.label) {
188 case 0: return [4 /*yield*/, buildHttpRequest(destination, requestConfig === null || requestConfig === void 0 ? void 0 : requestConfig.headers)];
189 case 1:
190 destinationRequestConfig = _a.sent();
191 request = requestConfig
192 ? merge(destinationRequestConfig, requestConfig)
193 : destinationRequestConfig;
194 return [2 /*return*/, __assign(__assign({}, getAxiosConfigWithDefaultsWithoutMethod()), request)];
195 }
196 });
197 });
198}
199exports.buildAxiosRequestConfig = buildAxiosRequestConfig;
200/**
201 * Builds a [[DestinationHttpRequestConfig]] for the given destination, merges it into the given requestConfig
202 * and executes it (using Axios).
203 * @param destination - A destination or a destination name and a JWT.
204 * @param requestConfig - Any object representing an HTTP request.
205 * @param options - An [[HttpRequestOptions]] of the http request for configuring e.g., csrf token delegation. By default, the SDK will not fetch the csrf token.
206 * @returns A promise resolving to an [[HttpResponse]].
207 */
208function executeHttpRequest(destination, requestConfig, options) {
209 return execute(executeWithAxios)(destination, requestConfig, options);
210}
211exports.executeHttpRequest = executeHttpRequest;
212function buildDestinationHttpRequestConfig(destination, headers) {
213 return __assign({ baseURL: destination.url, headers: headers, params: destination.queryParameters }, (0, http_agent_1.getAgentConfig)(destination));
214}
215function buildHeaders(destination, customHeaders) {
216 return (0, scp_cf_1.buildHeadersForDestination)(destination, customHeaders).catch(function (error) {
217 throw new util_1.ErrorWithCause('Failed to build headers.', error);
218 });
219}
220function resolveDestination(destination) {
221 return (0, scp_cf_1.useOrFetchDestination)(destination).catch(function (error) {
222 throw new util_1.ErrorWithCause('Failed to load destination.', error);
223 });
224}
225function merge(destinationRequestConfig, customRequestConfig) {
226 return __assign(__assign(__assign({}, destinationRequestConfig), customRequestConfig), { headers: __assign(__assign({}, destinationRequestConfig.headers), customRequestConfig.headers) });
227}
228function mergeRequestWithAxiosDefaults(request) {
229 return __assign(__assign({}, getAxiosConfigWithDefaults()), request);
230}
231function executeWithAxios(request) {
232 return axios_1.default.request(mergeRequestWithAxiosDefaults(request));
233}
234/**
235 * Builds an Axios config with default configuration i.e. no_proxy, default http and https agent and GET as request method.
236 * @returns AxiosRequestConfig with default parameters
237 */
238function getAxiosConfigWithDefaults() {
239 return __assign(__assign({}, getAxiosConfigWithDefaultsWithoutMethod()), { method: 'get' });
240}
241exports.getAxiosConfigWithDefaults = getAxiosConfigWithDefaults;
242function getAxiosConfigWithDefaultsWithoutMethod() {
243 return {
244 proxy: false,
245 httpAgent: new http.Agent(),
246 httpsAgent: new https.Agent(),
247 paramsSerializer: function (params) {
248 if (params === void 0) { params = {}; }
249 return Object.entries(params)
250 .map(function (_a) {
251 var key = _a[0], value = _a[1];
252 return "".concat(key, "=").concat(value);
253 })
254 .join('&');
255 }
256 };
257}
258exports.getAxiosConfigWithDefaultsWithoutMethod = getAxiosConfigWithDefaultsWithoutMethod;
259function getDefaultHttpRequestOptions() {
260 // TODO: 2.0 change to true
261 return {
262 fetchCsrfToken: false
263 };
264}
265function buildHttpRequestOptions(httpRequestOptions) {
266 return httpRequestOptions
267 ? __assign(__assign({}, getDefaultHttpRequestOptions()), httpRequestOptions) : getDefaultHttpRequestOptions();
268}
269function shouldHandleCsrfToken(requestConfig, options) {
270 return (!!options.fetchCsrfToken &&
271 requestConfig.method !== 'get' &&
272 requestConfig.method !== 'GET');
273}
274exports.shouldHandleCsrfToken = shouldHandleCsrfToken;
275function getCsrfHeaders(destination, request) {
276 return __awaiter(this, void 0, void 0, function () {
277 var csrfHeaders;
278 return __generator(this, function (_a) {
279 csrfHeaders = (0, util_1.pickIgnoreCase)(request.headers, 'x-csrf-token');
280 return [2 /*return*/, Object.keys(csrfHeaders).length
281 ? csrfHeaders
282 : (0, http_client_1.buildCsrfHeaders)(destination, {
283 params: request.params,
284 headers: request.headers,
285 url: request.url,
286 proxy: request.proxy,
287 httpAgent: request.httpAgent,
288 httpsAgent: request.httpsAgent
289 })];
290 });
291 });
292}
293function addCsrfTokenToHeader(destination, request, httpRequestOptions) {
294 return __awaiter(this, void 0, void 0, function () {
295 var options, csrfHeaders, _a;
296 return __generator(this, function (_b) {
297 switch (_b.label) {
298 case 0:
299 options = buildHttpRequestOptions(httpRequestOptions);
300 if (!shouldHandleCsrfToken(request, options)) return [3 /*break*/, 2];
301 return [4 /*yield*/, getCsrfHeaders(destination, request)];
302 case 1:
303 _a = _b.sent();
304 return [3 /*break*/, 3];
305 case 2:
306 _a = {};
307 _b.label = 3;
308 case 3:
309 csrfHeaders = _a;
310 return [2 /*return*/, __assign(__assign({}, request.headers), csrfHeaders)];
311 }
312 });
313 });
314}
315//# sourceMappingURL=http-client.js.map
\No newline at end of file