UNPKG

25.2 kBJavaScriptView Raw
1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT License. See License.txt in the project root for license information.
3import { __assign, __spreadArrays } from "tslib";
4import { isTokenCredential } from "@azure/core-auth";
5import { DefaultHttpClient } from "./defaultHttpClient";
6import { getPathStringFromParameter, getPathStringFromParameterPath, } from "./operationParameter";
7import { isStreamOperation } from "./operationSpec";
8import { deserializationPolicy, } from "./policies/deserializationPolicy";
9import { exponentialRetryPolicy } from "./policies/exponentialRetryPolicy";
10import { generateClientRequestIdPolicy } from "./policies/generateClientRequestIdPolicy";
11import { userAgentPolicy, getDefaultUserAgentHeaderName, getDefaultUserAgentValue, } from "./policies/userAgentPolicy";
12import { DefaultRedirectOptions, redirectPolicy } from "./policies/redirectPolicy";
13import { RequestPolicyOptions, } from "./policies/requestPolicy";
14import { rpRegistrationPolicy } from "./policies/rpRegistrationPolicy";
15import { signingPolicy } from "./policies/signingPolicy";
16import { systemErrorRetryPolicy } from "./policies/systemErrorRetryPolicy";
17import { QueryCollectionFormat } from "./queryCollectionFormat";
18import { MapperType } from "./serializer";
19import { URLBuilder } from "./url";
20import * as utils from "./util/utils";
21import { stringifyXML } from "./util/xml";
22import { isWebResourceLike, WebResource, } from "./webResource";
23import { agentPolicy } from "./policies/agentPolicy";
24import { proxyPolicy, getDefaultProxySettings } from "./policies/proxyPolicy";
25import { throttlingRetryPolicy } from "./policies/throttlingRetryPolicy";
26import { AzureIdentityCredentialAdapter, azureResourceManagerEndpoints, } from "./credentials/azureIdentityTokenCredentialAdapter";
27/**
28 * @class
29 * Initializes a new instance of the ServiceClient.
30 */
31var ServiceClient = /** @class */ (function () {
32 /**
33 * The ServiceClient constructor
34 * @constructor
35 * @param {ServiceClientCredentials} [credentials] The credentials object used for authentication.
36 * @param {ServiceClientOptions} [options] The service client options that govern the behavior of the client.
37 */
38 function ServiceClient(credentials, options) {
39 if (!options) {
40 options = {};
41 }
42 if (options.baseUri) {
43 this.baseUri = options.baseUri;
44 }
45 var serviceClientCredentials;
46 if (isTokenCredential(credentials)) {
47 var scope = undefined;
48 if ((options === null || options === void 0 ? void 0 : options.baseUri) && azureResourceManagerEndpoints.includes(options === null || options === void 0 ? void 0 : options.baseUri)) {
49 scope = options.baseUri + "/.default";
50 }
51 serviceClientCredentials = new AzureIdentityCredentialAdapter(credentials, scope);
52 }
53 else {
54 serviceClientCredentials = credentials;
55 }
56 if (serviceClientCredentials && !serviceClientCredentials.signRequest) {
57 throw new Error("credentials argument needs to implement signRequest method");
58 }
59 this._withCredentials = options.withCredentials || false;
60 this._httpClient = options.httpClient || new DefaultHttpClient();
61 this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger);
62 var requestPolicyFactories;
63 if (Array.isArray(options.requestPolicyFactories)) {
64 requestPolicyFactories = options.requestPolicyFactories;
65 }
66 else {
67 requestPolicyFactories = createDefaultRequestPolicyFactories(serviceClientCredentials, options);
68 if (options.requestPolicyFactories) {
69 var newRequestPolicyFactories = options.requestPolicyFactories(requestPolicyFactories);
70 if (newRequestPolicyFactories) {
71 requestPolicyFactories = newRequestPolicyFactories;
72 }
73 }
74 }
75 this._requestPolicyFactories = requestPolicyFactories;
76 }
77 /**
78 * Send the provided httpRequest.
79 */
80 ServiceClient.prototype.sendRequest = function (options) {
81 if (options === null || options === undefined || typeof options !== "object") {
82 throw new Error("options cannot be null or undefined and it must be of type object.");
83 }
84 var httpRequest;
85 try {
86 if (isWebResourceLike(options)) {
87 options.validateRequestProperties();
88 httpRequest = options;
89 }
90 else {
91 httpRequest = new WebResource();
92 httpRequest = httpRequest.prepare(options);
93 }
94 }
95 catch (error) {
96 return Promise.reject(error);
97 }
98 var httpPipeline = this._httpClient;
99 if (this._requestPolicyFactories && this._requestPolicyFactories.length > 0) {
100 for (var i = this._requestPolicyFactories.length - 1; i >= 0; --i) {
101 httpPipeline = this._requestPolicyFactories[i].create(httpPipeline, this._requestPolicyOptions);
102 }
103 }
104 return httpPipeline.sendRequest(httpRequest);
105 };
106 /**
107 * Send an HTTP request that is populated using the provided OperationSpec.
108 * @param {OperationArguments} operationArguments The arguments that the HTTP request's templated values will be populated from.
109 * @param {OperationSpec} operationSpec The OperationSpec to use to populate the httpRequest.
110 * @param {ServiceCallback} callback The callback to call when the response is received.
111 */
112 ServiceClient.prototype.sendOperationRequest = function (operationArguments, operationSpec, callback) {
113 if (typeof operationArguments.options === "function") {
114 callback = operationArguments.options;
115 operationArguments.options = undefined;
116 }
117 var httpRequest = new WebResource();
118 var result;
119 try {
120 var baseUri = operationSpec.baseUrl || this.baseUri;
121 if (!baseUri) {
122 throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a baseUri string property that contains the base URL to use.");
123 }
124 httpRequest.method = operationSpec.httpMethod;
125 httpRequest.operationSpec = operationSpec;
126 var requestUrl = URLBuilder.parse(baseUri);
127 if (operationSpec.path) {
128 requestUrl.appendPath(operationSpec.path);
129 }
130 if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) {
131 for (var _i = 0, _a = operationSpec.urlParameters; _i < _a.length; _i++) {
132 var urlParameter = _a[_i];
133 var urlParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, urlParameter, operationSpec.serializer);
134 urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter));
135 if (!urlParameter.skipEncoding) {
136 urlParameterValue = encodeURIComponent(urlParameterValue);
137 }
138 requestUrl.replaceAll("{" + (urlParameter.mapper.serializedName || getPathStringFromParameter(urlParameter)) + "}", urlParameterValue);
139 }
140 }
141 if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) {
142 for (var _b = 0, _c = operationSpec.queryParameters; _b < _c.length; _b++) {
143 var queryParameter = _c[_b];
144 var queryParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, queryParameter, operationSpec.serializer);
145 if (queryParameterValue != undefined) {
146 queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter));
147 if (queryParameter.collectionFormat != undefined) {
148 if (queryParameter.collectionFormat === QueryCollectionFormat.Multi) {
149 if (queryParameterValue.length === 0) {
150 queryParameterValue = "";
151 }
152 else {
153 for (var index in queryParameterValue) {
154 var item = queryParameterValue[index];
155 queryParameterValue[index] = item == undefined ? "" : item.toString();
156 }
157 }
158 }
159 else if (queryParameter.collectionFormat === QueryCollectionFormat.Ssv ||
160 queryParameter.collectionFormat === QueryCollectionFormat.Tsv) {
161 queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat);
162 }
163 }
164 if (!queryParameter.skipEncoding) {
165 if (Array.isArray(queryParameterValue)) {
166 for (var index in queryParameterValue) {
167 if (queryParameterValue[index] !== undefined &&
168 queryParameterValue[index] !== null) {
169 queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]);
170 }
171 }
172 }
173 else {
174 queryParameterValue = encodeURIComponent(queryParameterValue);
175 }
176 }
177 if (queryParameter.collectionFormat != undefined &&
178 queryParameter.collectionFormat !== QueryCollectionFormat.Multi &&
179 queryParameter.collectionFormat !== QueryCollectionFormat.Ssv &&
180 queryParameter.collectionFormat !== QueryCollectionFormat.Tsv) {
181 queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat);
182 }
183 requestUrl.setQueryParameter(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue);
184 }
185 }
186 }
187 httpRequest.url = requestUrl.toString();
188 var contentType = operationSpec.contentType || this.requestContentType;
189 if (contentType) {
190 httpRequest.headers.set("Content-Type", contentType);
191 }
192 if (operationSpec.headerParameters) {
193 for (var _d = 0, _e = operationSpec.headerParameters; _d < _e.length; _d++) {
194 var headerParameter = _e[_d];
195 var headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer);
196 if (headerValue != undefined) {
197 headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter));
198 var headerCollectionPrefix = headerParameter.mapper
199 .headerCollectionPrefix;
200 if (headerCollectionPrefix) {
201 for (var _f = 0, _g = Object.keys(headerValue); _f < _g.length; _f++) {
202 var key = _g[_f];
203 httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]);
204 }
205 }
206 else {
207 httpRequest.headers.set(headerParameter.mapper.serializedName ||
208 getPathStringFromParameter(headerParameter), headerValue);
209 }
210 }
211 }
212 }
213 var options = operationArguments.options;
214 if (options) {
215 if (options.customHeaders) {
216 for (var customHeaderName in options.customHeaders) {
217 httpRequest.headers.set(customHeaderName, options.customHeaders[customHeaderName]);
218 }
219 }
220 if (options.abortSignal) {
221 httpRequest.abortSignal = options.abortSignal;
222 }
223 if (options.timeout) {
224 httpRequest.timeout = options.timeout;
225 }
226 if (options.onUploadProgress) {
227 httpRequest.onUploadProgress = options.onUploadProgress;
228 }
229 if (options.onDownloadProgress) {
230 httpRequest.onDownloadProgress = options.onDownloadProgress;
231 }
232 }
233 httpRequest.withCredentials = this._withCredentials;
234 serializeRequestBody(this, httpRequest, operationArguments, operationSpec);
235 if (httpRequest.streamResponseBody == undefined) {
236 httpRequest.streamResponseBody = isStreamOperation(operationSpec);
237 }
238 result = this.sendRequest(httpRequest).then(function (res) {
239 return flattenResponse(res, operationSpec.responses[res.status]);
240 });
241 }
242 catch (error) {
243 result = Promise.reject(error);
244 }
245 var cb = callback;
246 if (cb) {
247 result
248 // tslint:disable-next-line:no-null-keyword
249 .then(function (res) { return cb(null, res._response.parsedBody, res._response.request, res._response); })
250 .catch(function (err) { return cb(err); });
251 }
252 return result;
253 };
254 return ServiceClient;
255}());
256export { ServiceClient };
257export function serializeRequestBody(serviceClient, httpRequest, operationArguments, operationSpec) {
258 if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
259 httpRequest.body = getOperationArgumentValueFromParameter(serviceClient, operationArguments, operationSpec.requestBody, operationSpec.serializer);
260 var bodyMapper = operationSpec.requestBody.mapper;
261 var required = bodyMapper.required, xmlName = bodyMapper.xmlName, xmlElementName = bodyMapper.xmlElementName, serializedName = bodyMapper.serializedName;
262 var typeName = bodyMapper.type.name;
263 try {
264 if (httpRequest.body != undefined || required) {
265 var requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody);
266 httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString);
267 var isStream = typeName === MapperType.Stream;
268 if (operationSpec.isXML) {
269 if (typeName === MapperType.Sequence) {
270 httpRequest.body = stringifyXML(utils.prepareXMLRootList(httpRequest.body, xmlElementName || xmlName || serializedName), { rootName: xmlName || serializedName });
271 }
272 else if (!isStream) {
273 httpRequest.body = stringifyXML(httpRequest.body, {
274 rootName: xmlName || serializedName,
275 });
276 }
277 }
278 else if (!isStream) {
279 httpRequest.body = JSON.stringify(httpRequest.body);
280 }
281 }
282 }
283 catch (error) {
284 throw new Error("Error \"" + error.message + "\" occurred in serializing the payload - " + JSON.stringify(serializedName, undefined, " ") + ".");
285 }
286 }
287 else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {
288 httpRequest.formData = {};
289 for (var _i = 0, _a = operationSpec.formDataParameters; _i < _a.length; _i++) {
290 var formDataParameter = _a[_i];
291 var formDataParameterValue = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer);
292 if (formDataParameterValue != undefined) {
293 var formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter);
294 httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter));
295 }
296 }
297 }
298}
299function isRequestPolicyFactory(instance) {
300 return typeof instance.create === "function";
301}
302function getValueOrFunctionResult(value, defaultValueCreator) {
303 var result;
304 if (typeof value === "string") {
305 result = value;
306 }
307 else {
308 result = defaultValueCreator();
309 if (typeof value === "function") {
310 result = value(result);
311 }
312 }
313 return result;
314}
315function createDefaultRequestPolicyFactories(credentials, options) {
316 var factories = [];
317 if (options.generateClientRequestIdHeader) {
318 factories.push(generateClientRequestIdPolicy(options.clientRequestIdHeaderName));
319 }
320 if (credentials) {
321 if (isRequestPolicyFactory(credentials)) {
322 factories.push(credentials);
323 }
324 else {
325 factories.push(signingPolicy(credentials));
326 }
327 }
328 var userAgentHeaderName = getValueOrFunctionResult(options.userAgentHeaderName, getDefaultUserAgentHeaderName);
329 var userAgentHeaderValue = getValueOrFunctionResult(options.userAgent, getDefaultUserAgentValue);
330 if (userAgentHeaderName && userAgentHeaderValue) {
331 factories.push(userAgentPolicy({ key: userAgentHeaderName, value: userAgentHeaderValue }));
332 }
333 var redirectOptions = __assign(__assign({}, DefaultRedirectOptions), options.redirectOptions);
334 if (redirectOptions.handleRedirects) {
335 factories.push(redirectPolicy(redirectOptions.maxRetries));
336 }
337 factories.push(rpRegistrationPolicy(options.rpRegistrationRetryTimeout));
338 if (!options.noRetryPolicy) {
339 factories.push(exponentialRetryPolicy());
340 factories.push(systemErrorRetryPolicy());
341 factories.push(throttlingRetryPolicy());
342 }
343 factories.push(deserializationPolicy(options.deserializationContentTypes));
344 var proxySettings = options.proxySettings || getDefaultProxySettings();
345 if (proxySettings) {
346 factories.push(proxyPolicy(proxySettings));
347 }
348 if (options.agentSettings) {
349 factories.push(agentPolicy(options.agentSettings));
350 }
351 return factories;
352}
353/**
354 * Get the property parent for the property at the provided path when starting with the provided
355 * parent object.
356 */
357export function getPropertyParent(parent, propertyPath) {
358 if (parent && propertyPath) {
359 var propertyPathLength = propertyPath.length;
360 for (var i = 0; i < propertyPathLength - 1; ++i) {
361 var propertyName = propertyPath[i];
362 if (!parent[propertyName]) {
363 parent[propertyName] = {};
364 }
365 parent = parent[propertyName];
366 }
367 }
368 return parent;
369}
370function getOperationArgumentValueFromParameter(serviceClient, operationArguments, parameter, serializer) {
371 return getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameter.parameterPath, parameter.mapper, serializer);
372}
373export function getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, serializer) {
374 var value;
375 if (typeof parameterPath === "string") {
376 parameterPath = [parameterPath];
377 }
378 if (Array.isArray(parameterPath)) {
379 if (parameterPath.length > 0) {
380 if (parameterMapper.isConstant) {
381 value = parameterMapper.defaultValue;
382 }
383 else {
384 var propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);
385 if (!propertySearchResult.propertyFound) {
386 propertySearchResult = getPropertyFromParameterPath(serviceClient, parameterPath);
387 }
388 var useDefaultValue = false;
389 if (!propertySearchResult.propertyFound) {
390 useDefaultValue =
391 parameterMapper.required ||
392 (parameterPath[0] === "options" && parameterPath.length === 2);
393 }
394 value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;
395 }
396 // Serialize just for validation purposes.
397 var parameterPathString = getPathStringFromParameterPath(parameterPath, parameterMapper);
398 serializer.serialize(parameterMapper, value, parameterPathString);
399 }
400 }
401 else {
402 if (parameterMapper.required) {
403 value = {};
404 }
405 for (var propertyName in parameterPath) {
406 var propertyMapper = parameterMapper.type.modelProperties[propertyName];
407 var propertyPath = parameterPath[propertyName];
408 var propertyValue = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer);
409 // Serialize just for validation purposes.
410 var propertyPathString = getPathStringFromParameterPath(propertyPath, propertyMapper);
411 serializer.serialize(propertyMapper, propertyValue, propertyPathString);
412 if (propertyValue !== undefined) {
413 if (!value) {
414 value = {};
415 }
416 value[propertyName] = propertyValue;
417 }
418 }
419 }
420 return value;
421}
422function getPropertyFromParameterPath(parent, parameterPath) {
423 var result = { propertyFound: false };
424 var i = 0;
425 for (; i < parameterPath.length; ++i) {
426 var parameterPathPart = parameterPath[i];
427 // Make sure to check inherited properties too, so don't use hasOwnProperty().
428 if (parent != undefined && parameterPathPart in parent) {
429 parent = parent[parameterPathPart];
430 }
431 else {
432 break;
433 }
434 }
435 if (i === parameterPath.length) {
436 result.propertyValue = parent;
437 result.propertyFound = true;
438 }
439 return result;
440}
441export function flattenResponse(_response, responseSpec) {
442 var parsedHeaders = _response.parsedHeaders;
443 var bodyMapper = responseSpec && responseSpec.bodyMapper;
444 var addOperationResponse = function (obj) {
445 return Object.defineProperty(obj, "_response", {
446 value: _response,
447 });
448 };
449 if (bodyMapper) {
450 var typeName = bodyMapper.type.name;
451 if (typeName === "Stream") {
452 return addOperationResponse(__assign(__assign({}, parsedHeaders), { blobBody: _response.blobBody, readableStreamBody: _response.readableStreamBody }));
453 }
454 var modelProperties_1 = (typeName === "Composite" && bodyMapper.type.modelProperties) || {};
455 var isPageableResponse = Object.keys(modelProperties_1).some(function (k) { return modelProperties_1[k].serializedName === ""; });
456 if (typeName === "Sequence" || isPageableResponse) {
457 // We're expecting a sequece(array) make sure that the response body is in the
458 // correct format, if not make it an empty array []
459 var parsedBody = Array.isArray(_response.parsedBody) ? _response.parsedBody : [];
460 var arrayResponse = __spreadArrays(parsedBody);
461 for (var _i = 0, _a = Object.keys(modelProperties_1); _i < _a.length; _i++) {
462 var key = _a[_i];
463 if (modelProperties_1[key].serializedName) {
464 arrayResponse[key] = _response.parsedBody[key];
465 }
466 }
467 if (parsedHeaders) {
468 for (var _b = 0, _c = Object.keys(parsedHeaders); _b < _c.length; _b++) {
469 var key = _c[_b];
470 arrayResponse[key] = parsedHeaders[key];
471 }
472 }
473 addOperationResponse(arrayResponse);
474 return arrayResponse;
475 }
476 if (typeName === "Composite" || typeName === "Dictionary") {
477 return addOperationResponse(__assign(__assign({}, parsedHeaders), _response.parsedBody));
478 }
479 }
480 if (bodyMapper ||
481 _response.request.method === "HEAD" ||
482 utils.isPrimitiveType(_response.parsedBody)) {
483 // primitive body types and HEAD booleans
484 return addOperationResponse(__assign(__assign({}, parsedHeaders), { body: _response.parsedBody }));
485 }
486 return addOperationResponse(__assign(__assign({}, parsedHeaders), _response.parsedBody));
487}
488//# sourceMappingURL=serviceClient.js.map
\No newline at end of file