-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathopenapi-request-builder.ts
More file actions
473 lines (432 loc) · 15.3 KB
/
Copy pathopenapi-request-builder.ts
File metadata and controls
473 lines (432 loc) · 15.3 KB
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
/* eslint-disable max-classes-per-file */
import {
createLogger,
ErrorWithCause,
isNullish,
pickValueIgnoreCase,
removeSlashes,
transformVariadicArgumentToArray,
unique
} from '@sap-cloud-sdk/util';
import { useOrFetchDestination } from '@sap-cloud-sdk/connectivity';
import {
assertHttpDestination,
noDestinationErrorMessage
} from '@sap-cloud-sdk/connectivity/internal';
import { executeHttpRequest } from '@sap-cloud-sdk/http-client';
import { filterCustomRequestConfig } from '@sap-cloud-sdk/http-client/internal';
import type {
Method,
HttpResponse,
HttpRequestConfigWithOrigin,
CustomRequestConfig
} from '@sap-cloud-sdk/http-client';
import type {
OriginOptions,
HttpMiddleware
} from '@sap-cloud-sdk/http-client/internal';
import type { HttpDestinationOrFetchOptions } from '@sap-cloud-sdk/connectivity';
import type { AxiosResponse } from 'axios';
const logger = createLogger({
package: 'openapi',
messageContext: 'openapi-request-builder'
});
/**
* @internal
*/
interface EncodingMetadata {
contentType: string;
isImplicit: boolean;
parsedContentTypes: {
type: string;
parameters: { [key: string]: string };
}[];
}
/**
* Builder class for constructing FormData from a request body with encoding metadata.
* @internal
*/
class FormDataBuilder {
constructor(
private readonly body: Record<string, any>,
private readonly encoding: Record<string, EncodingMetadata>
) {}
/**
* Build and return a FormData object from the body and encoding metadata.
* @returns The constructed FormData object.
*/
build(): FormData {
const formData = new FormData();
for (const [key, value] of Object.entries(this.body ?? {})) {
if (!this?.encoding[key]) {
throw new Error(
`Missing encoding metadata for property '${key}'. ` +
'This indicates a code generation issue. ' +
'Please regenerate your API client.'
);
}
const metadata = this.encoding[key];
const allowedTypes = new Set(
metadata.parsedContentTypes.map(ct => ct.type.toLowerCase())
);
const encoded: string | Blob =
value instanceof Blob
? this.encodeBlob({ key, value }, metadata)
: this.encodeString({ key, value }, metadata, allowedTypes);
formData.append(key, encoded);
}
return formData;
}
private checkIsFlexibleContentType(
metadata: EncodingMetadata,
allowedTypes: Set<string>
): boolean {
const { contentType: targetContentType, parsedContentTypes } = metadata;
return (
Boolean(targetContentType) &&
(targetContentType.includes('*') ||
parsedContentTypes.length > 1 ||
allowedTypes.has('any'))
);
}
/**
* Encode a Blob value for FormData with appropriate content type handling.
* @param params - The key and value to encode.
* @param params.key - The field name.
* @param params.value - The Blob value to encode.
* @param metadata - Encoding metadata for this field.
* @returns Blob - The encoded Blob value.
*/
private encodeBlob(
{
key,
value
}: {
key: string;
value: Blob;
},
metadata: EncodingMetadata
): Blob {
const {
contentType: targetContentType,
isImplicit: targetIsImplicit,
parsedContentTypes
} = metadata;
const allowedTypes = new Set(
parsedContentTypes.map(ct => ct.type.toLowerCase())
);
const isFlexibleContentType = this.checkIsFlexibleContentType(
metadata,
allowedTypes
);
// If `Blob` has no type, we use value from the specification unless the target content type is complex (multiple choices or wildcards)
if (
!value.type &&
!isFlexibleContentType &&
// If the encoding has additional requirements regarding parameters (e.g. charset)
// we don't want to add a content type that may not meet those requirements,
// even if the main type should match - in that case the user should provide a Blob with appropriate content type themselves
!Object.keys(parsedContentTypes[0].parameters).length
) {
logger.debug(
`Adding missing content type '${targetContentType}' to Blob for key '${key}' as per encoding specification.`
);
const withType = new Blob([value], {
type: targetContentType
});
return withType;
}
// If `Blob` has a type, we do a surface-level check to warn users about potential mismatches with the specification
// unless the target content type is complex (multiple choices or wildcards)
// or the encoding is implicit (in which case we are more lenient as there was no specific request from the spec)
const valueContentTypeBase = value.type.split(';')[0].trim();
if (
// Don't warn about implicit encodings (less likely to be relevant)
!targetIsImplicit &&
// We do not handle more complex content types
!isFlexibleContentType &&
// Do the actual comparison
valueContentTypeBase.toLowerCase() !== targetContentType.toLowerCase()
) {
logger.warn(
`Content type mismatch for key '${key}': value has type '${value.type}' but encoding specifies '${targetContentType}'.`
);
}
return value;
}
/**
* Encode a string value for FormData with appropriate content type and charset handling.
* @param params - The key and value to encode.
* @param params.key - The field name.
* @param params.value - The value to encode.
* @param metadata - Encoding metadata for this field.
* @param allowedTypes - Set of allowed content types for this field.
* @returns Blob or string - The encoded value.
*/
private encodeString(
{
key,
value
}: {
key: string;
value: any;
},
metadata: EncodingMetadata,
allowedTypes: Set<string>
): string | Blob {
// Handle string data
// Only use JSON.stringify for application/json content type - otherwise may unduly escape e.g. stringified XML
// To avoid stringifying pre-stringified JSON, users should use `Blob` or raw `FormData`
const stringValue = allowedTypes.has('application/json')
? JSON.stringify(value)
: String(value);
// If a charset is specified in the encoding, we encode the string accordingly (if unambiguous)
const targetCharset = unique(
metadata.parsedContentTypes.map(ct => ct.parameters.charset)
);
if (targetCharset.length !== 1 || !targetCharset[0]) {
return stringValue;
}
const targetCharsetValue = targetCharset[0];
// Wrap in try-catch to provide better error message if charset encoding fails (e.g. due to unsupported charset or invalid characters for the charset)
let buffer: Buffer;
try {
buffer = Buffer.from(stringValue, targetCharsetValue as BufferEncoding);
} catch (e: any) {
throw new ErrorWithCause(
`Failed to encode form data field '${key}' with charset '${targetCharsetValue}'.`,
e
);
}
// Encode as Blob with appropriate content type if unambiguous
const isFlexibleContentType = this.checkIsFlexibleContentType(
metadata,
allowedTypes
);
const maybeContentType = !isFlexibleContentType
? { type: metadata.contentType }
: undefined;
const blob = new Blob([buffer], maybeContentType);
return blob;
}
}
/**
* Request builder for OpenAPI requests.
* @template ResponseT - Type of the response for the request.
*/
export class OpenApiRequestBuilder<ResponseT = any> {
private _fetchCsrfToken = true;
private customHeaders: Record<string, string> = {};
private customRequestConfiguration: CustomRequestConfig = {};
private _middlewares: HttpMiddleware[] = [];
/**
* Create an instance of `OpenApiRequestBuilder`.
* @param method - HTTP method of the request to be built.
* @param pathPattern - Path for the request containing path parameter references as in the OpenAPI specification.
* @param parameters - Query parameters and or body to pass to the request.
* @param basePath - The custom path to be prefixed to the API path pattern.
*/
constructor(
public method: Method,
private pathPattern: string,
private parameters?: OpenApiRequestParameters,
private basePath?: string
) {}
/**
* Add custom headers to the request. If a header field with the given name already exists it is overwritten.
* @param headers - Key-value pairs denoting additional custom headers.
* @returns The request builder itself, to facilitate method chaining.
*/
addCustomHeaders(headers: Record<string, string>): this {
Object.entries(headers).forEach(([key, value]) => {
this.customHeaders[key.toLowerCase()] = value;
});
return this;
}
/**
* Add custom request configuration to the request. Typically, this is used when specifying response type for downloading files.
* If the custom request configuration contains keys in this list {@link @sap-cloud-sdk/http-client!defaultDisallowedKeys}, they will be removed.
* @param requestConfiguration - Key-value pairs denoting additional custom request configuration options to be set in the request.
* @returns The request builder itself, to facilitate method chaining.
*/
addCustomRequestConfiguration(
requestConfiguration: CustomRequestConfig
): this {
Object.entries(requestConfiguration).forEach(([key, value]) => {
this.customRequestConfiguration[key] = value;
});
return this;
}
/**
* Skip fetching csrf token for this request, which is typically useful when the csrf token is not required.
* @returns The request builder itself, to facilitate method chaining.
*/
skipCsrfTokenFetching(): this {
this._fetchCsrfToken = false;
return this;
}
/**
* Set middleware for requests towards the target system given in the destination.
* @param middlewares - Middlewares to be applied to the executeHttpRequest().
* @returns The request builder itself, to facilitate method chaining.
*/
middleware(middlewares: HttpMiddleware | HttpMiddleware[]): this;
middleware(...middlewares: HttpMiddleware[]): this;
middleware(
first: undefined | HttpMiddleware | HttpMiddleware[],
...rest: HttpMiddleware[]
): this {
this._middlewares = transformVariadicArgumentToArray(first, rest);
return this;
}
/**
* Execute request and get a raw {@link @sap-cloud-sdk/http-client!HttpResponse}, including all information about the HTTP response.
* This especially comes in handy, when you need to access the headers or status code of the response.
* @param destination - Destination or DestinationFetchOptions to execute the request against.
* @returns A promise resolving to an {@link @sap-cloud-sdk/http-client!HttpResponse}.
*/
async executeRaw(
destination: HttpDestinationOrFetchOptions
): Promise<HttpResponse> {
const fetchCsrfToken =
this._fetchCsrfToken &&
['post', 'put', 'patch', 'delete'].includes(this.method.toLowerCase());
const resolvedDestination = await useOrFetchDestination(destination);
if (isNullish(destination)) {
throw Error(noDestinationErrorMessage(destination));
}
assertHttpDestination(resolvedDestination!);
return executeHttpRequest(resolvedDestination, await this.requestConfig(), {
fetchCsrfToken
});
}
/**
* Execute request and get the response data. Use this to conveniently access the data of a service without technical information about the response.
* @param destination - Destination or DestinationFetchOptions to execute the request against.
* @returns A promise resolving to the requested return type.
*/
async execute(
destination: HttpDestinationOrFetchOptions
): Promise<ResponseT> {
const response = await this.executeRaw(destination);
if (isAxiosResponse(response)) {
return response.data;
}
throw new Error(
'Could not access response data. Response was not an axios response.'
);
}
/**
* Set the custom base path that gets prefixed to the API path parameter before a request.
* @param basePath - Base path to be set.
* @returns The request builder itself, to facilitate method chaining.
*/
setBasePath(basePath: string): this {
this.basePath = basePath;
return this;
}
/**
* Get HTTP request config.
* @returns Promise of the HTTP request config with origin.
*/
protected async requestConfig(): Promise<HttpRequestConfigWithOrigin> {
const defaultConfig = {
method: this.method,
url: this.getPath(),
headers: this.getHeaders(),
params: this.getParameters(),
middleware: this._middlewares,
data: this.getBody()
};
return {
...defaultConfig,
...filterCustomRequestConfig(this.customRequestConfiguration)
};
}
private getHeaders(): OriginOptions {
const headerParameters = { ...(this.parameters?.headerParameters || {}) };
const body = this.parameters?.body;
if (
body instanceof Blob &&
body.type &&
!pickValueIgnoreCase(headerParameters, 'content-type')
) {
headerParameters['content-type'] = body.type;
}
const options = { requestConfig: headerParameters };
if (Object.keys(this.customHeaders).length) {
return { custom: this.customHeaders, ...options };
}
return options;
}
private getParameters(): OriginOptions {
return { requestConfig: this.parameters?.queryParameters || {} };
}
private getBody(): any {
const body = this.parameters?.body;
const contentType = pickValueIgnoreCase(
this.parameters?.headerParameters,
'content-type'
);
// Handle multipart/form-data body unless the body is already a FormData instance
if (contentType === 'multipart/form-data' && !(body instanceof FormData)) {
const encoding = this.parameters!._encoding!;
const builder = new FormDataBuilder(body, encoding);
return builder.build();
}
return body;
}
private getPath(): string {
const pathParameters = this.parameters?.pathParameters || {};
// Get the innermost curly bracket pairs with non-empty and legal content as placeholders.
const placeholders: string[] = this.pathPattern.match(/{[^/?#{}]+}/g) || [];
return (
(this.basePath ? removeSlashes(this.basePath) : '') +
placeholders.reduce((path: string, placeholder: string) => {
const strippedPlaceholder = placeholder.slice(1, -1);
const parameterValue = pathParameters[strippedPlaceholder];
return path.replace(placeholder, encodeURIComponent(parameterValue));
}, this.pathPattern)
);
}
}
// TODO: Tighten types
/**
* Type of the request parameters to be passed to {@link OpenApiRequestBuilder}.
*/
export interface OpenApiRequestParameters {
/**
* Collection of path parameters.
*/
pathParameters?: Record<string, any>;
/**
* Collection of query parameters.
*/
queryParameters?: Record<string, any>;
/**
* Collection of header parameters.
*/
headerParameters?: Record<string, any>;
/**
* Request body typically used with "create" and "update" operations (POST, PUT, PATCH).
*/
body?: any;
/**
* Encoding metadata for multipart/form-data properties.
* @internal
*/
_encoding?: Record<
string,
{
contentType: string;
isImplicit: boolean;
parsedContentTypes: {
type: string;
parameters: { [key: string]: string };
}[];
}
>;
}
function isAxiosResponse(val: any): val is AxiosResponse {
return 'data' in val;
}