-
Notifications
You must be signed in to change notification settings - Fork 10
/
request.ts
697 lines (595 loc) · 18.6 KB
/
request.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
import attempt from "@newdash/newdash/attempt";
import { Mutex } from "@newdash/newdash/functional/Mutex";
import join from "@newdash/newdash/join";
import slice from "@newdash/newdash/slice";
import startsWith from "@newdash/newdash/startsWith";
import { JsonBatchResponseBundle } from "@odata/parser/lib/builder/batch";
import { RequestInit } from "node-fetch";
import { v4 } from "uuid";
import { BatchRequest, formatBatchRequest, formatBatchRequestForOData401, parseMultiPartContent } from "./batch";
import { EntitySet } from "./entityset";
import { FrameworkError, ODataServerError, ValidationError } from "./errors";
import { ODataFilter } from "./filter";
import { ClientCredentialsOAuthClient } from "./oauth";
import { ODataParam, ODataQueryParam } from "./params";
import {
BatchRequestOptions, BatchRequests,
BatchResponses, Credential, FetchProxy, HTTPMethod,
ODataActionImportRequest,
ODataActionRequest, ODataFunctionImportRequest, ODataFunctionRequest, ODataNewOptions,
ODataQueryRequest, ODataReadIDRequest, ODataVariant, ODataWriteRequest, PlainODataMultiResponse,
PlainODataResponse, PlainODataSingleResponse, SAPNetweaverOData
} from "./types";
import { ODataV4, ODataVersion } from "./types_v4";
import { GetAuthorizationPair } from "./util";
const S_X_CSRF_TOKEN = "x-csrf-token";
const S_CONTENT_TYPE = "Content-Type";
// @ts-ignore
const defaultProxy: FetchProxy = async(url: string, init?: RequestInit) => {
// @ts-ignore
const res = await fetch(url, init);
let content: any = await res.text();
if (res.headers.has(S_CONTENT_TYPE) && startsWith(res.headers.get(S_CONTENT_TYPE), "application/json")) {
const jsonResult = attempt(JSON.parse, content);
// supress error
if (!(jsonResult instanceof Error)) {
content = jsonResult;
}
}
return {
content,
response: res
};
};
/**
* OData Client
*/
export class OData {
private metadataUri: string;
/**
* odata service path, like /sap/c4c/odata/v1/c4codata/
*/
private serviceRoot: string;
/**
* http basic credential
*/
private credential: Credential;
/**
* oauth client
*/
private oauthClient: ClientCredentialsOAuthClient;
/**
* internal csrf token
*/
private csrfToken = "";
/**
* dont direct use this object
*
* use client.getHeaders()
*
*/
private commonHeader: { [headerName: string]: string } = {
"Accept": "application/json",
[S_CONTENT_TYPE]: "application/json"
};
private fetchProxy = defaultProxy;
private processCsrfToken = false;
private csrfTokenName: string = S_X_CSRF_TOKEN;
private variant: ODataVariant = "default";
private version: ODataVersion = "v2";
private lock: Mutex = new Mutex();
/**
* alternative constructor
*
* @param options config options
*/
public static New(options: ODataNewOptions): OData {
const rt = new OData(
options.metadataUri,
options.credential,
undefined,
undefined,
options.fetchProxy,
options.processCsrfToken
);
rt.version = options.version ?? "v2";
rt.variant = options.variant ?? "default";
// force process csrf token
if (SAPNetweaverOData.includes(rt.variant)) {
rt.processCsrfToken = true;
// ref https://cxwiki.sap.com/pages/viewpage.action?pageId=511350333
// use compatibility mode for c4c/byd
rt.commonHeader["odata-v2-strict-json-format"] = "true";
}
rt.csrfTokenName = options.csrfTokenName ?? S_X_CSRF_TOKEN;
return rt;
}
/**
* create odata client instance for odata v4
*
* @param options
*/
static New4(options: ODataNewOptions): ODataV4 {
options.version = "v4";
// @ts-ignore
return OData.New(options);
}
/**
* new odata query param
*/
static newParam(): ODataQueryParam {
return ODataParam.newParam();
}
/**
* new filter
*/
static newFilter(): ODataFilter {
return ODataFilter.newFilter();
}
/**
* OData
*
* @deprecated please use static method create instance
* @private
*/
private constructor(
metadataUri: string,
credential?: Credential,
headers: any = {},
/**
* deprecated, DO NOT use it
*/
urlRewrite?: (string) => string,
fetchProxy?: FetchProxy,
/**
* auto fetch csrf token before broken operation
*/
processCsrfToken = false
) {
if (fetchProxy) {
this.fetchProxy = fetchProxy;
}
if (metadataUri === undefined) {
throw new ValidationError("metadata url required !");
} else {
this.metadataUri = metadataUri;
// e.g https://c4c-system/sap/c4c/odata/v1/c4codata/
this.serviceRoot =
`${join(slice(this.metadataUri.split("/"), 0, -1), "/")}/`;
if (credential) {
this.credential = credential;
if (credential.tokenUrl && credential.clientId && credential.clientSecret) {
this.oauthClient = new ClientCredentialsOAuthClient(
credential.tokenUrl,
credential.clientId,
credential.clientSecret,
);
}
}
}
this.commonHeader = { ...this.commonHeader, ...headers };
this.processCsrfToken = processCsrfToken;
}
/**
* generate dynamic header
*/
private async getHeaders() {
let rt = { ...this.commonHeader };
if (this.credential) {
if (this.credential.username !== undefined) {
rt = {
...rt,
...GetAuthorizationPair(this.credential.username, this.credential.password)
};
} else if (this.oauthClient) {
rt = {
...rt,
... (await this.oauthClient.getHeader())
};
}
}
if (this.processCsrfToken) {
rt[this.csrfTokenName] = await this.getCsrfToken();
}
return rt;
}
/**
* getEntitySet
*
* @param entitySetName the name of entity set, you can get it from metadata
*
*/
public getEntitySet<T = any>(entitySetName: string): EntitySet<T> {
return new EntitySet(entitySetName, this);
}
/**
* Set OData Client Http Basic credential
*
* @param credential
*/
public setCredential(credential: Credential): void {
this.credential = credential;
}
/**
* setODataEndPath
*
* e.g. https://tenant.c4c.saphybriscloud.cn/sap/c4c/odata/v1/c4codata/
*/
public setODataEndPath(odataEnd: string): void {
if (odataEnd !== undefined) {
this.serviceRoot = odataEnd;
if (!this.serviceRoot.endsWith("/")) {
this.serviceRoot += "/";
}
}
}
public getVersion(): ODataVersion {
return this.version;
}
/**
* fetch CSRF Token
*
* @param withCache set to `false` if you want to force to retrieve the refresh csrf token
* @returns
*/
public async getCsrfToken(withCache = true) {
return this.lock.use(async () => {
if (withCache && this.csrfToken !== undefined && this.csrfToken !== null && this.csrfToken?.length > 0) {
return this.csrfToken;
}
const config: RequestInit = {
method: "GET",
headers: { [this.csrfTokenName]: "fetch" }
};
if (this.credential) {
config.headers = {
...config.headers,
...GetAuthorizationPair(this.credential.username, this.credential.password)
};
}
const { response: { headers } } = await this.fetchProxy(this.serviceRoot, config);
if (headers) {
this.csrfToken = headers.get(this.csrfTokenName);
} else {
throw new FrameworkError("csrf token need the odata proxy give out headers!");
}
return this.csrfToken;
});
}
public cleanCsrfToken(): void {
if (this.csrfToken) { delete this.csrfToken; }
}
/**
* odata request uri
*
* @param uri HTTP URI
* @param queryParams odata query params
* @param method HTTP method
* @param body request content
*/
private async requestUri<T = any>(
uri: string,
queryParams?: ODataQueryParam,
method: HTTPMethod = "GET",
body?: any
): Promise<PlainODataMultiResponse<T>> {
const finalUri = uri;
const config: RequestInit = { method, headers: await this.getHeaders() };
// format body
if (method !== "GET" && body) {
if (typeof body !== "string") {
config.body = JSON.stringify(body);
} else {
config.body = body;
}
}
// request & response
let res = await this.fetchProxy(finalUri, config);
// one time retry if csrf token time expired
if (this.processCsrfToken) {
if (res.response.headers) {
if (res.response.headers.get(this.csrfTokenName)?.toUpperCase() === "Required".toUpperCase()) {
this.cleanCsrfToken();
config.headers[this.csrfTokenName] = await this.getCsrfToken();
res = await this.fetchProxy(finalUri, config);
}
}
}
const { content } = res;
return content;
}
/**
* odata request
*
* @param collection CollectionName
* @param id entity uuid or compound key
* @param queryParams query param, not work for single entity uri
* @param method request method
* @param entity odata Entity instance
*/
private async _executeDataOperation<T = any>(
collection: string,
id?: any,
queryParams?: ODataQueryParam,
method: HTTPMethod = "GET",
entity?: any
) {
let url = `${this.serviceRoot}${collection}`;
if (id) {
url += this.formatIdString(id);
}
const query = queryParams?.toString?.(this.version);
if (query !== undefined && query.length > 0) {
url = `${url}?${query}`;
}
return this.requestUri<T>(url, queryParams, method, entity);
}
async actionImport(actionName: string, parameters?: any, params: ODataQueryParam = this.newParam()) {
return this.newRequest({
method: "POST",
params,
parameters,
actionName
});
}
async functionImport(functionName: string, parameters?: any, params: ODataQueryParam = this.newParam()) {
return await this.newRequest({
parameters,
params,
method: "GET",
functionName
});
}
/**
* format id part of url
*
* @param id
*
* @example
*
* ```ts
* this.formatIdString(1) // => '(1)'
* this.formatIdString({UUID:'xxx'}) // => '(UUID='xxx')'
* ```
*/
private formatIdString(id: any): string {
let rt = "";
switch (typeof id) {
// for compound key like
// Alphabetical_list_of_products(CategoryName='Beverages',Discontinued=false,ProductID=1,ProductName='Chai')
case "object":
const compoundId = Object.entries(id).map((kv) => {
const k = kv[0];
const v = kv[1];
switch (typeof v) {
case "string":
return `${k}='${v}'`;
case "number":
return `${k}=${v}`;
case "boolean":
return `${k}=${v}`;
default:
if (v === null) {
return `${k}=null`;
}
// other type will be removed
return "";
}
}).filter((v) => v).join(",");
rt = `(${compoundId})`;
break;
case "number":
rt = `(${id})`;
break;
case "string":
if (this.variant === "cap") {
rt = `(${id})`; // for cap framework, id string should remove singlequote
} else {
rt = `('${id}')`;
}
break;
case "undefined":
break;
default:
throw new FrameworkError(`Not supported ObjectID type ${typeof id} for request`);
}
return rt;
}
/**
* new odata http request
*/
public async newRequest<T = any>(options: ODataQueryRequest): Promise<PlainODataMultiResponse<T>>;
public async newRequest<T = any>(options: ODataWriteRequest<T>): Promise<PlainODataSingleResponse<T>>;
public async newRequest<T = any>(options: ODataReadIDRequest): Promise<PlainODataSingleResponse<T>>;
public async newRequest(options: ODataFunctionRequest): Promise<PlainODataResponse>;
public async newRequest(options: ODataActionRequest): Promise<PlainODataResponse>;
public async newRequest(options: ODataFunctionImportRequest): Promise<PlainODataResponse>;
public async newRequest(options: ODataActionImportRequest): Promise<PlainODataResponse>;
public async newRequest(options: any): Promise<any> {
if (options.actionName || options.functionName) {
return this._executeActionOrFunction(options);
}
return this._executeDataOperation(options.collection, options.id, options.params, options.method, options.entity);
}
private async _executeActionOrFunction(options: ODataActionRequest)
private async _executeActionOrFunction(options: ODataFunctionRequest)
private async _executeActionOrFunction(options: ODataFunctionImportRequest)
private async _executeActionOrFunction(options: ODataActionImportRequest)
private async _executeActionOrFunction(options: any) {
let url = `${this.serviceRoot}`; // create new string
let method: HTTPMethod = "GET";
options.params = options.params ?? this.newParam();
/**
* is bounded operation, means the operation maybe affected to a specific instance
*/
const isBoundedOperation = ((options.collection !== undefined) && (options.id !== undefined));
const actionName = options["actionName"];
const functionName = options["functionName"];
const isAction = (typeof actionName === "string");
const isFunction = (typeof functionName === "string");
if (isAction && isFunction) {
throw new ValidationError(`'actionName' and 'functionName' can not be fillled in same time.`);
}
if (!isAction && !isFunction) {
throw new ValidationError(`must provide 'actionName' or 'functionName'.`);
}
// if is bound operation, add the collection and key here
if (isBoundedOperation) {
url += `${options.collection}`;
url += this.formatIdString(options.id);
}
if (!url.endsWith("/")) { url += "/"; }
if (isFunction) {
url += `${functionName}`;
method = "GET";
switch (this.version) {
case "v2":
if (options.parameters !== undefined) {
// convert function parameters to params custom params
options.params = options.params ?? this.newParam();
Object
.entries(options.parameters)
.forEach(([key, value]) => {
options.params.custom(key, value);
});
}
break;
case "v4":
if (options.parameters !== undefined) {
url += this.formatIdString(options.parameters);
} else {
url += "()";
}
break;
default:
break;
}
}
if (isAction) {
url += `${actionName}`;
method = "POST";
}
// append query to uru
const query = options?.params?.toString?.(this.version);
if (query !== undefined && query.length > 0) {
url += `?${query}`;
}
if (isAction) {
// action with payload
return this.requestUri(url, undefined, method, options.parameters ?? {});
}
if (isFunction) {
return this.requestUri(url, undefined, method);
}
}
/**
* format batch request parameter
*/
private async formatBatchRequests(requests: Array<Promise<BatchRequest>>) {
const url = `${this.serviceRoot}$batch`;
const req: RequestInit = {
method: "POST",
headers: await this.getHeaders()
};
// format promised requests
const r = await Promise.all(requests.map(async(aBatchR) => await aBatchR));
const requestBoundaryString = v4();
req.headers["Content-Type"] = `multipart/mixed; boundary=${requestBoundaryString}`;
req.body = formatBatchRequest(r, requestBoundaryString);
return { url, req };
}
/**
* execute batch requests and get response
*
* @param requests batch request
*/
public async execBatchRequests<T extends BatchRequests = any>(requests: T): BatchResponses<T> {
const { url, req } = await this.formatBatchRequests(requests);
const { content, response: { headers } } = await this.fetchProxy(url, req);
const responseBoundaryString = headers.get("Content-Type").split("=").pop();
if (responseBoundaryString.length == 0) {
// if boundary string empty, error here
}
// @ts-ignore
return await parseMultiPartContent(content, responseBoundaryString);
}
/**
* execute batch requests in OData V4.01 Json format, and get response
*
* @param requests
*/
public async execBatchRequestsJson<T extends BatchRequests = any>(requests: T): BatchResponses<T> {
// TO DO, verify odata version here
const reqs = await Promise.all(requests);
const body = formatBatchRequestForOData401(reqs);
const url = `${this.serviceRoot}$batch`;
const headers = await this.getHeaders();
const response = await this.fetchProxy(url, { method: "POST", body: JSON.stringify(body), headers });
const responseBody: JsonBatchResponseBundle = response.content;
if (responseBody["error"]) {
throw new ODataServerError(responseBody["error"]["message"] || "Unknown server error");
}
const rt = [];
responseBody.responses?.forEach((responseItem) => {
rt.push({
json: async() => responseItem.body,
text: async() => JSON.stringify(responseItem.body),
headers: responseItem.headers,
status: responseItem.status,
statusText: undefined,
raw: responseItem
});
});
// @ts-ignore
return rt;
}
/**
* create new filter
*
* @alias OData.newFilter
*/
public newFilter() {
return OData.newFilter();
}
/**
* create new param
*
* @alias OData.newParam
*/
public newParam() {
return OData.newParam();
}
public async newBatchRequest<T>(options: BatchRequestOptions<T>) {
let { withContentLength = false } = options;
const { collection, method = "GET", id, params, entity } = options;
if (SAPNetweaverOData.includes(this.variant)) {
// for SAP NetWeaver Platform OData, need content length header
withContentLength = true;
}
let url = collection;
const headers = Object.assign({}, this.commonHeader); // clone
const rt: BatchRequest<T> = { url, init: { method, headers, body: "" } };
if (id) {
url += this.formatIdString(id);
}
// READ OPERATION
if (method === "GET" || method === "DELETE") {
delete headers["Content-Type"];
// other request don't need param
if (params) {
url = `${url}?${params.toString(this.version)}`;
}
}
// WRITE OPERATION
else {
rt.init.body = entity;
if (withContentLength) {
rt.init.headers["Content-Length"] = encodeURI(rt.init.body.toString()).length;
}
}
rt.init.headers = headers;
rt.url = url;
rt.options = options;
return rt;
}
}