-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
serviceClient.ts
1066 lines (969 loc) · 36.1 KB
/
serviceClient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { TokenCredential, isTokenCredential } from "@azure/core-auth";
import { DefaultHttpClient } from "./defaultHttpClient";
import { HttpClient } from "./httpClient";
import { HttpOperationResponse, RestResponse } from "./httpOperationResponse";
import { HttpPipelineLogger } from "./httpPipelineLogger";
import { logPolicy, LogPolicyOptions } from "./policies/logPolicy";
import { OperationArguments } from "./operationArguments";
import {
getPathStringFromParameter,
getPathStringFromParameterPath,
OperationParameter,
ParameterPath
} from "./operationParameter";
import { isStreamOperation, OperationSpec } from "./operationSpec";
import {
deserializationPolicy,
DeserializationContentTypes,
DefaultDeserializationOptions
} from "./policies/deserializationPolicy";
import { exponentialRetryPolicy, DefaultRetryOptions } from "./policies/exponentialRetryPolicy";
import { generateClientRequestIdPolicy } from "./policies/generateClientRequestIdPolicy";
import {
userAgentPolicy,
getDefaultUserAgentHeaderName,
getDefaultUserAgentValue
} from "./policies/userAgentPolicy";
import { redirectPolicy, DefaultRedirectOptions } from "./policies/redirectPolicy";
import {
RequestPolicy,
RequestPolicyFactory,
RequestPolicyOptions
} from "./policies/requestPolicy";
import { rpRegistrationPolicy } from "./policies/rpRegistrationPolicy";
import { bearerTokenAuthenticationPolicy } from "./policies/bearerTokenAuthenticationPolicy";
import { systemErrorRetryPolicy } from "./policies/systemErrorRetryPolicy";
import { QueryCollectionFormat } from "./queryCollectionFormat";
import { CompositeMapper, DictionaryMapper, Mapper, MapperType, Serializer } from "./serializer";
import { URLBuilder } from "./url";
import * as utils from "./util/utils";
import { stringifyXML } from "./util/xml";
import {
RequestOptionsBase,
RequestPrepareOptions,
WebResource,
WebResourceLike,
isWebResourceLike
} from "./webResource";
import { OperationResponse } from "./operationResponse";
import { ServiceCallback, isNode } from "./util/utils";
import { proxyPolicy } from "./policies/proxyPolicy";
import { throttlingRetryPolicy } from "./policies/throttlingRetryPolicy";
import { ServiceClientCredentials } from "./credentials/serviceClientCredentials";
import { signingPolicy } from "./policies/signingPolicy";
import { logger } from "./log";
import { InternalPipelineOptions } from "./pipelineOptions";
import { DefaultKeepAliveOptions, keepAlivePolicy } from "./policies/keepAlivePolicy";
import { tracingPolicy } from "./policies/tracingPolicy";
import { disableResponseDecompressionPolicy } from "./policies/disableResponseDecompressionPolicy";
import { ndJsonPolicy } from "./policies/ndJsonPolicy";
import { XML_ATTRKEY, SerializerOptions, XML_CHARKEY } from "./util/serializer.common";
import { URL } from "./url";
/**
* Options to configure a proxy for outgoing requests (Node.js only).
*/
export interface ProxySettings {
/**
* The proxy's host address.
*/
host: string;
/**
* The proxy host's port.
*/
port: number;
/**
* The user name to authenticate with the proxy, if required.
*/
username?: string;
/**
* The password to authenticate with the proxy, if required.
*/
password?: string;
}
export type ProxyOptions = ProxySettings; // Alias ProxySettings as ProxyOptions for future use.
/**
* Options to be provided while creating the client.
*/
export interface ServiceClientOptions {
/**
* An array of factories which get called to create the RequestPolicy pipeline used to send a HTTP
* request on the wire, or a function that takes in the defaultRequestPolicyFactories and returns
* the requestPolicyFactories that will be used.
*/
requestPolicyFactories?:
| RequestPolicyFactory[]
| ((defaultRequestPolicyFactories: RequestPolicyFactory[]) => void | RequestPolicyFactory[]);
/**
* The HttpClient that will be used to send HTTP requests.
*/
httpClient?: HttpClient;
/**
* The HttpPipelineLogger that can be used to debug RequestPolicies within the HTTP pipeline.
*/
httpPipelineLogger?: HttpPipelineLogger;
/**
* If set to true, turn off the default retry policy.
*/
noRetryPolicy?: boolean;
/**
* Gets or sets the retry timeout in seconds for AutomaticRPRegistration. Default value is 30.
*/
rpRegistrationRetryTimeout?: number;
/**
* Whether or not to generate a client request ID header for each HTTP request.
*/
generateClientRequestIdHeader?: boolean;
/**
* Whether to include credentials in CORS requests in the browser.
* See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials for more information.
*/
withCredentials?: boolean;
/**
* If specified, a GenerateRequestIdPolicy will be added to the HTTP pipeline that will add a
* header to all outgoing requests with this header name and a random UUID as the request ID.
*/
clientRequestIdHeaderName?: string;
/**
* The content-types that will be associated with JSON or XML serialization.
*/
deserializationContentTypes?: DeserializationContentTypes;
/**
* The header name to use for the telemetry header while sending the request. If this is not
* specified, then "User-Agent" will be used when running on Node.js and "x-ms-useragent" will
* be used when running in a browser.
*/
userAgentHeaderName?: string | ((defaultUserAgentHeaderName: string) => string);
/**
* The string to be set to the telemetry header while sending the request, or a function that
* takes in the default user-agent string and returns the user-agent string that will be used.
*/
userAgent?: string | ((defaultUserAgent: string) => string);
/**
* Proxy settings which will be used for every HTTP request (Node.js only).
*/
proxySettings?: ProxySettings;
/**
* If specified, will be used to build the BearerTokenAuthenticationPolicy.
*/
credentialScopes?: string | string[];
}
/**
* @class
* Initializes a new instance of the ServiceClient.
*/
export class ServiceClient {
/**
* If specified, this is the base URI that requests will be made against for this ServiceClient.
* If it is not specified, then all OperationSpecs must contain a baseUrl property.
*/
protected baseUri?: string;
/**
* The default request content type for the service.
* Used if no requestContentType is present on an OperationSpec.
*/
protected requestContentType?: string;
/**
* The HTTP client that will be used to send requests.
*/
private readonly _httpClient: HttpClient;
private readonly _requestPolicyOptions: RequestPolicyOptions;
private readonly _requestPolicyFactories: RequestPolicyFactory[];
private readonly _withCredentials: boolean;
/**
* The ServiceClient constructor
* @constructor
* @param credentials The credentials used for authentication with the service.
* @param options The service client options that govern the behavior of the client.
*/
constructor(
credentials?: TokenCredential | ServiceClientCredentials,
/* eslint-disable-next-line @azure/azure-sdk/ts-naming-options */
options?: ServiceClientOptions
) {
if (!options) {
options = {};
}
this._withCredentials = options.withCredentials || false;
this._httpClient = options.httpClient || new DefaultHttpClient();
this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger);
let requestPolicyFactories: RequestPolicyFactory[];
if (Array.isArray(options.requestPolicyFactories)) {
logger.info("ServiceClient: using custom request policies");
requestPolicyFactories = options.requestPolicyFactories;
} else {
let authPolicyFactory: RequestPolicyFactory | undefined = undefined;
if (isTokenCredential(credentials)) {
logger.info(
"ServiceClient: creating bearer token authentication policy from provided credentials"
);
// Create a wrapped RequestPolicyFactory here so that we can provide the
// correct scope to the BearerTokenAuthenticationPolicy at the first time
// one is requested. This is needed because generated ServiceClient
// implementations do not set baseUri until after ServiceClient's constructor
// is finished, leaving baseUri empty at the time when it is needed to
// build the correct scope name.
const wrappedPolicyFactory: () => RequestPolicyFactory = () => {
let bearerTokenPolicyFactory: RequestPolicyFactory | undefined = undefined;
// eslint-disable-next-line @typescript-eslint/no-this-alias
const serviceClient = this;
const serviceClientOptions = options;
return {
create(nextPolicy: RequestPolicy, createOptions: RequestPolicyOptions): RequestPolicy {
const credentialScopes = getCredentialScopes(
serviceClientOptions,
serviceClient.baseUri
);
if (!credentialScopes) {
throw new Error(
`When using credential, the ServiceClient must contain a baseUri or a credentialScopes in ServiceClientOptions. Unable to create a bearerTokenAuthenticationPolicy`
);
}
if (bearerTokenPolicyFactory === undefined || bearerTokenPolicyFactory === null) {
bearerTokenPolicyFactory = bearerTokenAuthenticationPolicy(
credentials,
credentialScopes
);
}
return bearerTokenPolicyFactory.create(nextPolicy, createOptions);
}
};
};
authPolicyFactory = wrappedPolicyFactory();
} else if (credentials && typeof credentials.signRequest === "function") {
logger.info("ServiceClient: creating signing policy from provided credentials");
authPolicyFactory = signingPolicy(credentials);
} else if (credentials !== undefined && credentials !== null) {
throw new Error("The credentials argument must implement the TokenCredential interface");
}
logger.info("ServiceClient: using default request policies");
requestPolicyFactories = createDefaultRequestPolicyFactories(authPolicyFactory, options);
if (options.requestPolicyFactories) {
// options.requestPolicyFactories can also be a function that manipulates
// the default requestPolicyFactories array
const newRequestPolicyFactories:
| void
| RequestPolicyFactory[] = options.requestPolicyFactories(requestPolicyFactories);
if (newRequestPolicyFactories) {
requestPolicyFactories = newRequestPolicyFactories;
}
}
}
this._requestPolicyFactories = requestPolicyFactories;
}
/**
* Send the provided httpRequest.
*/
sendRequest(options: RequestPrepareOptions | WebResourceLike): Promise<HttpOperationResponse> {
if (options === null || options === undefined || typeof options !== "object") {
throw new Error("options cannot be null or undefined and it must be of type object.");
}
let httpRequest: WebResourceLike;
try {
if (isWebResourceLike(options)) {
options.validateRequestProperties();
httpRequest = options;
} else {
httpRequest = new WebResource();
httpRequest = httpRequest.prepare(options);
}
} catch (error) {
return Promise.reject(error);
}
let httpPipeline: RequestPolicy = this._httpClient;
if (this._requestPolicyFactories && this._requestPolicyFactories.length > 0) {
for (let i = this._requestPolicyFactories.length - 1; i >= 0; --i) {
httpPipeline = this._requestPolicyFactories[i].create(
httpPipeline,
this._requestPolicyOptions
);
}
}
return httpPipeline.sendRequest(httpRequest);
}
/**
* Send an HTTP request that is populated using the provided OperationSpec.
* @param {OperationArguments} operationArguments The arguments that the HTTP request's templated values will be populated from.
* @param {OperationSpec} operationSpec The OperationSpec to use to populate the httpRequest.
* @param {ServiceCallback} callback The callback to call when the response is received.
*/
async sendOperationRequest(
operationArguments: OperationArguments,
operationSpec: OperationSpec,
callback?: ServiceCallback<any>
): Promise<RestResponse> {
if (typeof operationArguments.options === "function") {
callback = operationArguments.options;
operationArguments.options = undefined;
}
const serializerOptions = operationArguments.options?.serializerOptions;
const httpRequest: WebResourceLike = new WebResource();
let result: Promise<RestResponse>;
try {
const baseUri: string | undefined = operationSpec.baseUrl || this.baseUri;
if (!baseUri) {
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."
);
}
httpRequest.method = operationSpec.httpMethod;
httpRequest.operationSpec = operationSpec;
const requestUrl: URLBuilder = URLBuilder.parse(baseUri);
if (operationSpec.path) {
requestUrl.appendPath(operationSpec.path);
}
if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) {
for (const urlParameter of operationSpec.urlParameters) {
let urlParameterValue: string = getOperationArgumentValueFromParameter(
this,
operationArguments,
urlParameter,
operationSpec.serializer
);
urlParameterValue = operationSpec.serializer.serialize(
urlParameter.mapper,
urlParameterValue,
getPathStringFromParameter(urlParameter),
serializerOptions
);
if (!urlParameter.skipEncoding) {
urlParameterValue = encodeURIComponent(urlParameterValue);
}
requestUrl.replaceAll(
`{${urlParameter.mapper.serializedName || getPathStringFromParameter(urlParameter)}}`,
urlParameterValue
);
}
}
if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) {
for (const queryParameter of operationSpec.queryParameters) {
let queryParameterValue: any = getOperationArgumentValueFromParameter(
this,
operationArguments,
queryParameter,
operationSpec.serializer
);
if (queryParameterValue !== undefined && queryParameterValue !== null) {
queryParameterValue = operationSpec.serializer.serialize(
queryParameter.mapper,
queryParameterValue,
getPathStringFromParameter(queryParameter),
serializerOptions
);
if (
queryParameter.collectionFormat !== undefined &&
queryParameter.collectionFormat !== null
) {
if (queryParameter.collectionFormat === QueryCollectionFormat.Multi) {
if (queryParameterValue.length === 0) {
// The collection is empty, no need to try serializing the current queryParam
continue;
} else {
for (const index in queryParameterValue) {
const item = queryParameterValue[index];
queryParameterValue[index] =
item === undefined || item === null ? "" : item.toString();
}
}
} else if (
queryParameter.collectionFormat === QueryCollectionFormat.Ssv ||
queryParameter.collectionFormat === QueryCollectionFormat.Tsv
) {
queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat);
}
}
if (!queryParameter.skipEncoding) {
if (Array.isArray(queryParameterValue)) {
for (const index in queryParameterValue) {
if (
queryParameterValue[index] !== undefined &&
queryParameterValue[index] !== null
) {
queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]);
}
}
} else {
queryParameterValue = encodeURIComponent(queryParameterValue);
}
}
if (
queryParameter.collectionFormat !== undefined &&
queryParameter.collectionFormat !== null &&
queryParameter.collectionFormat !== QueryCollectionFormat.Multi &&
queryParameter.collectionFormat !== QueryCollectionFormat.Ssv &&
queryParameter.collectionFormat !== QueryCollectionFormat.Tsv
) {
queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat);
}
requestUrl.setQueryParameter(
queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter),
queryParameterValue
);
}
}
}
httpRequest.url = requestUrl.toString();
const contentType = operationSpec.contentType || this.requestContentType;
if (contentType) {
httpRequest.headers.set("Content-Type", contentType);
}
if (operationSpec.headerParameters) {
for (const headerParameter of operationSpec.headerParameters) {
let headerValue: any = getOperationArgumentValueFromParameter(
this,
operationArguments,
headerParameter,
operationSpec.serializer
);
if (headerValue !== undefined && headerValue !== null) {
headerValue = operationSpec.serializer.serialize(
headerParameter.mapper,
headerValue,
getPathStringFromParameter(headerParameter),
serializerOptions
);
const headerCollectionPrefix = (headerParameter.mapper as DictionaryMapper)
.headerCollectionPrefix;
if (headerCollectionPrefix) {
for (const key of Object.keys(headerValue)) {
httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]);
}
} else {
httpRequest.headers.set(
headerParameter.mapper.serializedName ||
getPathStringFromParameter(headerParameter),
headerValue
);
}
}
}
}
const options: RequestOptionsBase | undefined = operationArguments.options;
if (options) {
if (options.customHeaders) {
for (const customHeaderName in options.customHeaders) {
httpRequest.headers.set(customHeaderName, options.customHeaders[customHeaderName]);
}
}
if (options.abortSignal) {
httpRequest.abortSignal = options.abortSignal;
}
if (options.timeout) {
httpRequest.timeout = options.timeout;
}
if (options.onUploadProgress) {
httpRequest.onUploadProgress = options.onUploadProgress;
}
if (options.onDownloadProgress) {
httpRequest.onDownloadProgress = options.onDownloadProgress;
}
if (options.spanOptions) {
httpRequest.spanOptions = options.spanOptions;
}
if (options.shouldDeserialize !== undefined && options.shouldDeserialize !== null) {
httpRequest.shouldDeserialize = options.shouldDeserialize;
}
}
httpRequest.withCredentials = this._withCredentials;
serializeRequestBody(this, httpRequest, operationArguments, operationSpec);
if (httpRequest.streamResponseBody === undefined || httpRequest.streamResponseBody === null) {
httpRequest.streamResponseBody = isStreamOperation(operationSpec);
}
let rawResponse: HttpOperationResponse;
let sendRequestError;
try {
rawResponse = await this.sendRequest(httpRequest);
} catch (error) {
sendRequestError = error;
}
if (sendRequestError) {
if (sendRequestError.response) {
sendRequestError.details = flattenResponse(
sendRequestError.response,
operationSpec.responses[sendRequestError.statusCode] ||
operationSpec.responses["default"]
);
}
result = Promise.reject(sendRequestError);
} else {
result = Promise.resolve(
flattenResponse(rawResponse!, operationSpec.responses[rawResponse!.status])
);
}
} catch (error) {
result = Promise.reject(error);
}
const cb = callback;
if (cb) {
result
.then((res) => cb(null, res._response.parsedBody, res._response.request, res._response))
.catch((err) => cb(err));
}
return result;
}
}
export function serializeRequestBody(
serviceClient: ServiceClient,
httpRequest: WebResourceLike,
operationArguments: OperationArguments,
operationSpec: OperationSpec
): void {
const serializerOptions = operationArguments.options?.serializerOptions ?? {};
const updatedOptions: Required<SerializerOptions> = {
rootName: serializerOptions.rootName ?? "",
includeRoot: serializerOptions.includeRoot ?? false,
xmlCharKey: serializerOptions.xmlCharKey ?? XML_CHARKEY
};
const xmlCharKey = serializerOptions.xmlCharKey;
if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
httpRequest.body = getOperationArgumentValueFromParameter(
serviceClient,
operationArguments,
operationSpec.requestBody,
operationSpec.serializer
);
const bodyMapper = operationSpec.requestBody.mapper;
const {
required,
xmlName,
xmlElementName,
serializedName,
xmlNamespace,
xmlNamespacePrefix
} = bodyMapper;
const typeName = bodyMapper.type.name;
try {
if ((httpRequest.body !== undefined && httpRequest.body !== null) || required) {
const requestBodyParameterPathString: string = getPathStringFromParameter(
operationSpec.requestBody
);
httpRequest.body = operationSpec.serializer.serialize(
bodyMapper,
httpRequest.body,
requestBodyParameterPathString,
updatedOptions
);
const isStream = typeName === MapperType.Stream;
if (operationSpec.isXML) {
const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns";
const value = getXmlValueWithNamespace(
xmlNamespace,
xmlnsKey,
typeName,
httpRequest.body,
updatedOptions
);
if (typeName === MapperType.Sequence) {
httpRequest.body = stringifyXML(
utils.prepareXMLRootList(
value,
xmlElementName || xmlName || serializedName!,
xmlnsKey,
xmlNamespace
),
{
rootName: xmlName || serializedName,
xmlCharKey
}
);
} else if (!isStream) {
httpRequest.body = stringifyXML(value, {
rootName: xmlName || serializedName,
xmlCharKey
});
}
} else if (
typeName === MapperType.String &&
(operationSpec.contentType?.match("text/plain") || operationSpec.mediaType === "text")
) {
// the String serializer has validated that request body is a string
// so just send the string.
return;
} else if (!isStream) {
httpRequest.body = JSON.stringify(httpRequest.body);
}
}
} catch (error) {
throw new Error(
`Error "${error.message}" occurred in serializing the payload - ${JSON.stringify(
serializedName,
undefined,
" "
)}.`
);
}
} else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {
httpRequest.formData = {};
for (const formDataParameter of operationSpec.formDataParameters) {
const formDataParameterValue: any = getOperationArgumentValueFromParameter(
serviceClient,
operationArguments,
formDataParameter,
operationSpec.serializer
);
if (formDataParameterValue !== undefined && formDataParameterValue !== null) {
const formDataParameterPropertyName: string =
formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter);
httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(
formDataParameter.mapper,
formDataParameterValue,
getPathStringFromParameter(formDataParameter),
updatedOptions
);
}
}
}
}
/**
* Adds an xml namespace to the xml serialized object if needed, otherwise it just returns the value itself
*/
function getXmlValueWithNamespace(
xmlNamespace: string | undefined,
xmlnsKey: string,
typeName: string,
serializedValue: any,
options: Required<SerializerOptions>
): any {
// Composite and Sequence schemas already got their root namespace set during serialization
// We just need to add xmlns to the other schema types
if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) {
const result: any = {};
result[options.xmlCharKey] = serializedValue;
result[XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace };
return result;
}
return serializedValue;
}
function getValueOrFunctionResult(
value: undefined | string | ((defaultValue: string) => string),
defaultValueCreator: () => string
): string {
let result: string;
if (typeof value === "string") {
result = value;
} else {
result = defaultValueCreator();
if (typeof value === "function") {
result = value(result);
}
}
return result;
}
function createDefaultRequestPolicyFactories(
authPolicyFactory: RequestPolicyFactory | undefined,
options: ServiceClientOptions
): RequestPolicyFactory[] {
const factories: RequestPolicyFactory[] = [];
if (options.generateClientRequestIdHeader) {
factories.push(generateClientRequestIdPolicy(options.clientRequestIdHeaderName));
}
if (authPolicyFactory) {
factories.push(authPolicyFactory);
}
const userAgentHeaderName: string = getValueOrFunctionResult(
options.userAgentHeaderName,
getDefaultUserAgentHeaderName
);
const userAgentHeaderValue: string = getValueOrFunctionResult(
options.userAgent,
getDefaultUserAgentValue
);
if (userAgentHeaderName && userAgentHeaderValue) {
factories.push(userAgentPolicy({ key: userAgentHeaderName, value: userAgentHeaderValue }));
}
factories.push(redirectPolicy());
factories.push(rpRegistrationPolicy(options.rpRegistrationRetryTimeout));
if (!options.noRetryPolicy) {
factories.push(exponentialRetryPolicy());
factories.push(systemErrorRetryPolicy());
factories.push(throttlingRetryPolicy());
}
factories.push(deserializationPolicy(options.deserializationContentTypes));
if (isNode) {
factories.push(proxyPolicy(options.proxySettings));
}
factories.push(logPolicy({ logger: logger.info }));
return factories;
}
export function createPipelineFromOptions(
pipelineOptions: InternalPipelineOptions,
authPolicyFactory?: RequestPolicyFactory
): ServiceClientOptions {
const requestPolicyFactories: RequestPolicyFactory[] = [];
if (pipelineOptions.sendStreamingJson) {
requestPolicyFactories.push(ndJsonPolicy());
}
let userAgentValue = undefined;
if (pipelineOptions.userAgentOptions && pipelineOptions.userAgentOptions.userAgentPrefix) {
const userAgentInfo: string[] = [];
userAgentInfo.push(pipelineOptions.userAgentOptions.userAgentPrefix);
// Add the default user agent value if it isn't already specified
// by the userAgentPrefix option.
const defaultUserAgentInfo = getDefaultUserAgentValue();
if (userAgentInfo.indexOf(defaultUserAgentInfo) === -1) {
userAgentInfo.push(defaultUserAgentInfo);
}
userAgentValue = userAgentInfo.join(" ");
}
const keepAliveOptions = {
...DefaultKeepAliveOptions,
...pipelineOptions.keepAliveOptions
};
const retryOptions = {
...DefaultRetryOptions,
...pipelineOptions.retryOptions
};
const redirectOptions = {
...DefaultRedirectOptions,
...pipelineOptions.redirectOptions
};
if (isNode) {
requestPolicyFactories.push(proxyPolicy(pipelineOptions.proxyOptions));
}
const deserializationOptions = {
...DefaultDeserializationOptions,
...pipelineOptions.deserializationOptions
};
const loggingOptions: LogPolicyOptions = {
...pipelineOptions.loggingOptions
};
requestPolicyFactories.push(
tracingPolicy({ userAgent: userAgentValue }),
keepAlivePolicy(keepAliveOptions),
userAgentPolicy({ value: userAgentValue }),
generateClientRequestIdPolicy(),
deserializationPolicy(deserializationOptions.expectedContentTypes),
throttlingRetryPolicy(),
systemErrorRetryPolicy(),
exponentialRetryPolicy(
retryOptions.maxRetries,
retryOptions.retryDelayInMs,
retryOptions.maxRetryDelayInMs
)
);
if (redirectOptions.handleRedirects) {
requestPolicyFactories.push(redirectPolicy(redirectOptions.maxRetries));
}
if (authPolicyFactory) {
requestPolicyFactories.push(authPolicyFactory);
}
requestPolicyFactories.push(logPolicy(loggingOptions));
if (isNode && pipelineOptions.decompressResponse === false) {
requestPolicyFactories.push(disableResponseDecompressionPolicy());
}
return {
httpClient: pipelineOptions.httpClient,
requestPolicyFactories
};
}
export type PropertyParent = { [propertyName: string]: any };
/**
* Get the property parent for the property at the provided path when starting with the provided
* parent object.
*/
export function getPropertyParent(parent: PropertyParent, propertyPath: string[]): PropertyParent {
if (parent && propertyPath) {
const propertyPathLength: number = propertyPath.length;
for (let i = 0; i < propertyPathLength - 1; ++i) {
const propertyName: string = propertyPath[i];
if (!parent[propertyName]) {
parent[propertyName] = {};
}
parent = parent[propertyName];
}
}
return parent;
}
function getOperationArgumentValueFromParameter(
serviceClient: ServiceClient,
operationArguments: OperationArguments,
parameter: OperationParameter,
serializer: Serializer
): any {
return getOperationArgumentValueFromParameterPath(
serviceClient,
operationArguments,
parameter.parameterPath,
parameter.mapper,
serializer
);
}
export function getOperationArgumentValueFromParameterPath(
serviceClient: ServiceClient,
operationArguments: OperationArguments,
parameterPath: ParameterPath,
parameterMapper: Mapper,
serializer: Serializer
): any {
let value: any;
if (typeof parameterPath === "string") {
parameterPath = [parameterPath];
}
const serializerOptions = operationArguments.options?.serializerOptions;
if (Array.isArray(parameterPath)) {
if (parameterPath.length > 0) {
if (parameterMapper.isConstant) {
value = parameterMapper.defaultValue;
} else {
let propertySearchResult: PropertySearchResult = getPropertyFromParameterPath(
operationArguments,
parameterPath
);
if (!propertySearchResult.propertyFound) {
propertySearchResult = getPropertyFromParameterPath(serviceClient, parameterPath);
}
let useDefaultValue = false;
if (!propertySearchResult.propertyFound) {
useDefaultValue =
parameterMapper.required ||
(parameterPath[0] === "options" && parameterPath.length === 2);
}
value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;
}
// Serialize just for validation purposes.
const parameterPathString: string = getPathStringFromParameterPath(
parameterPath,
parameterMapper
);
serializer.serialize(parameterMapper, value, parameterPathString, serializerOptions);
}
} else {
if (parameterMapper.required) {
value = {};
}
for (const propertyName in parameterPath) {
const propertyMapper: Mapper = (parameterMapper as CompositeMapper).type.modelProperties![
propertyName
];
const propertyPath: ParameterPath = parameterPath[propertyName];
const propertyValue: any = getOperationArgumentValueFromParameterPath(
serviceClient,
operationArguments,
propertyPath,
propertyMapper,
serializer
);
// Serialize just for validation purposes.
const propertyPathString: string = getPathStringFromParameterPath(
propertyPath,
propertyMapper
);
serializer.serialize(propertyMapper, propertyValue, propertyPathString, serializerOptions);
if (propertyValue !== undefined && propertyValue !== null) {
if (!value) {
value = {};
}
value[propertyName] = propertyValue;
}
}
}
return value;
}
interface PropertySearchResult {
propertyValue?: any;
propertyFound: boolean;
}
function getPropertyFromParameterPath(
parent: { [parameterName: string]: any },
parameterPath: string[]
): PropertySearchResult {
const result: PropertySearchResult = { propertyFound: false };
let i = 0;
for (; i < parameterPath.length; ++i) {
const parameterPathPart: string = parameterPath[i];
// Make sure to check inherited properties too, so don't use hasOwnProperty().
if (parent !== undefined && parent !== null && parameterPathPart in parent) {
parent = parent[parameterPathPart];
} else {
break;
}
}
if (i === parameterPath.length) {
result.propertyValue = parent;
result.propertyFound = true;
}
return result;
}
export function flattenResponse(
_response: HttpOperationResponse,
responseSpec: OperationResponse | undefined
): RestResponse {
const parsedHeaders = _response.parsedHeaders;
const bodyMapper = responseSpec && responseSpec.bodyMapper;
const addOperationResponse = (
obj: Record<string, unknown>
): {
_response: HttpOperationResponse;
} => {
return Object.defineProperty(obj, "_response", {
value: _response
});
};
if (bodyMapper) {
const typeName = bodyMapper.type.name;
if (typeName === "Stream") {
return addOperationResponse({
...parsedHeaders,
blobBody: _response.blobBody,
readableStreamBody: _response.readableStreamBody
});
}