serviceClient.js 22 KB

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