-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
serializationPolicy.ts
267 lines (249 loc) · 8.35 KB
/
serializationPolicy.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { PipelineResponse, SendRequest, PipelinePolicy } from "@azure/core-rest-pipeline";
import {
OperationRequest,
SerializerOptions,
XmlOptions,
XML_CHARKEY,
RequiredSerializerOptions,
OperationArguments,
XML_ATTRKEY,
OperationSpec,
DictionaryMapper
} from "./interfaces";
import { MapperTypeNames } from "./serializer";
import { getPathStringFromParameter } from "./interfaceHelpers";
import {
getOperationArgumentValueFromParameter,
getOperationRequestInfo
} from "./operationHelpers";
/**
* The programmatic identifier of the serializationPolicy.
*/
export const serializationPolicyName = "serializationPolicy";
/**
* Options to configure API request serialization.
*/
export interface SerializationPolicyOptions {
/**
* A function that is able to write XML. Required for XML support.
*/
stringifyXML?: (obj: any, opts?: XmlOptions) => string;
/**
* Configures behavior of xml parser and builder.
*/
serializerOptions?: SerializerOptions;
}
/**
* This policy handles assembling the request body and headers using
* an OperationSpec and OperationArguments on the request.
*/
export function serializationPolicy(options: SerializationPolicyOptions = {}): PipelinePolicy {
const stringifyXML = options.stringifyXML;
return {
name: serializationPolicyName,
async sendRequest(request: OperationRequest, next: SendRequest): Promise<PipelineResponse> {
const operationInfo = getOperationRequestInfo(request);
const operationSpec = operationInfo?.operationSpec;
const operationArguments = operationInfo?.operationArguments;
if (operationSpec && operationArguments) {
serializeHeaders(request, operationArguments, operationSpec);
serializeRequestBody(request, operationArguments, operationSpec, stringifyXML);
}
return next(request);
}
};
}
/**
* @internal
*/
export function serializeHeaders(
request: OperationRequest,
operationArguments: OperationArguments,
operationSpec: OperationSpec
): void {
if (operationSpec.headerParameters) {
for (const headerParameter of operationSpec.headerParameters) {
let headerValue = getOperationArgumentValueFromParameter(operationArguments, headerParameter);
if ((headerValue !== null && headerValue !== undefined) || headerParameter.mapper.required) {
headerValue = operationSpec.serializer.serialize(
headerParameter.mapper,
headerValue,
getPathStringFromParameter(headerParameter)
);
const headerCollectionPrefix = (headerParameter.mapper as DictionaryMapper)
.headerCollectionPrefix;
if (headerCollectionPrefix) {
for (const key of Object.keys(headerValue)) {
request.headers.set(headerCollectionPrefix + key, headerValue[key]);
}
} else {
request.headers.set(
headerParameter.mapper.serializedName || getPathStringFromParameter(headerParameter),
headerValue
);
}
}
}
}
const customHeaders = operationArguments.options?.requestOptions?.customHeaders;
if (customHeaders) {
for (const customHeaderName of Object.keys(customHeaders)) {
request.headers.set(customHeaderName, customHeaders[customHeaderName]);
}
}
}
/**
* @internal
*/
export function serializeRequestBody(
request: OperationRequest,
operationArguments: OperationArguments,
operationSpec: OperationSpec,
stringifyXML: (obj: any, opts?: XmlOptions) => string = function() {
throw new Error("XML serialization unsupported!");
}
): void {
const serializerOptions = operationArguments.options?.serializerOptions;
const updatedOptions: RequiredSerializerOptions = {
xml: {
rootName: serializerOptions?.xml.rootName ?? "",
includeRoot: serializerOptions?.xml.includeRoot ?? false,
xmlCharKey: serializerOptions?.xml.xmlCharKey ?? XML_CHARKEY
}
};
const xmlCharKey = updatedOptions.xml.xmlCharKey;
if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
request.body = getOperationArgumentValueFromParameter(
operationArguments,
operationSpec.requestBody
);
const bodyMapper = operationSpec.requestBody.mapper;
const {
required,
serializedName,
xmlName,
xmlElementName,
xmlNamespace,
xmlNamespacePrefix,
nullable
} = bodyMapper;
const typeName = bodyMapper.type.name;
try {
if (
(request.body !== undefined && request.body !== null) ||
(nullable && request.body === null) ||
required
) {
const requestBodyParameterPathString: string = getPathStringFromParameter(
operationSpec.requestBody
);
request.body = operationSpec.serializer.serialize(
bodyMapper,
request.body,
requestBodyParameterPathString,
updatedOptions
);
const isStream = typeName === MapperTypeNames.Stream;
if (operationSpec.isXML) {
const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns";
const value = getXmlValueWithNamespace(
xmlNamespace,
xmlnsKey,
typeName,
request.body,
updatedOptions
);
if (typeName === MapperTypeNames.Sequence) {
request.body = stringifyXML(
prepareXMLRootList(
value,
xmlElementName || xmlName || serializedName!,
xmlnsKey,
xmlNamespace
),
{ rootName: xmlName || serializedName, xmlCharKey }
);
} else if (!isStream) {
request.body = stringifyXML(value, {
rootName: xmlName || serializedName,
xmlCharKey
});
}
} else if (
typeName === MapperTypeNames.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) {
request.body = JSON.stringify(request.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) {
request.formData = {};
for (const formDataParameter of operationSpec.formDataParameters) {
const formDataParameterValue = getOperationArgumentValueFromParameter(
operationArguments,
formDataParameter
);
if (formDataParameterValue !== undefined && formDataParameterValue !== null) {
const formDataParameterPropertyName: string =
formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter);
request.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: RequiredSerializerOptions
): 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.xml.xmlCharKey] = serializedValue;
result[XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace };
return result;
}
return serializedValue;
}
function prepareXMLRootList(
obj: any,
elementName: string,
xmlNamespaceKey?: string,
xmlNamespace?: string
): { [key: string]: any[] } {
if (!Array.isArray(obj)) {
obj = [obj];
}
if (!xmlNamespaceKey || !xmlNamespace) {
return { [elementName]: obj };
}
const result = { [elementName]: obj };
result[XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace };
return result;
}