- Notifications
You must be signed in to change notification settings - Fork 231
/
Copy pathBatchRequestContent.ts
485 lines (464 loc) · 16.4 KB
/
BatchRequestContent.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
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module BatchRequestContent
*/
import{RequestMethod}from"../RequestMethod";
/**
* @interface
* Signature to represent the buffer request body parsing method
* @property {Function} buffer - Returns a promise that resolves to a buffer of the request body
*/
interfaceNodeBody{
buffer(): Promise<Buffer>;
}
/**
* @interface
* Signature to represent the Request for both Node and browser environments
* @extends Request
* @extends NodeBody
*/
interfaceIsomorphicRequestextendsRequest,NodeBody{}
/**
* @interface
* Signature representing BatchRequestStep data
* @property {string} id - Unique identity for the request, Should not be an empty string
* @property {string[]} [dependsOn] - Array of dependencies
* @property {Request} request - The Request object
*/
exportinterfaceBatchRequestStep{
id: string;
dependsOn?: string[];
request: Request;
}
/**
* @interface
* Signature representing single request in a Batching
* @extends RequestInit
* @see {@link https://github.com/Microsoft/TypeScript/blob/main/lib/lib.dom.d.ts#L1337} and {@link https://fetch.spec.whatwg.org/#requestinit}
*
* @property {string} url - The url value of the request
*/
exportinterfaceRequestDataextendsRequestInit{
url: string;
}
/**
* @interface
* Signature representing batch request data
* @property {string} id - Unique identity for the request, Should not be an empty string
* @property {string[]} [dependsOn] - Array of dependencies
*/
exportinterfaceBatchRequestDataextendsRequestData{
id: string;
dependsOn?: string[];
}
/**
* @interface
* Signature representing batch request body
* @property {BatchRequestData[]} requests - Array of request data, a json representation of requests for batch
*/
exportinterfaceBatchRequestBody{
requests: BatchRequestData[];
}
/**
* @class
* Class for handling BatchRequestContent
*/
exportclassBatchRequestContent{
/**
* @private
* @static
* Limit for number of requests {@link - https://developer.microsoft.com/en-us/graph/docs/concepts/known_issues#json-batching}
*/
privatestaticrequestLimit=20;
/**
* @public
* To keep track of requests, key will be id of the request and value will be the request json
*/
publicrequests: Map<string,BatchRequestStep>;
/**
* @private
* @static
* Validates the dependency chain of the requests
*
* Note:
* Individual requests can depend on other individual requests. Currently, requests can only depend on a single other request, and must follow one of these three patterns:
* 1. Parallel - no individual request states a dependency in the dependsOn property.
* 2. Serial - all individual requests depend on the previous individual request.
* 3. Same - all individual requests that state a dependency in the dependsOn property, state the same dependency.
* As JSON batching matures, these limitations will be removed.
* @see {@link https://developer.microsoft.com/en-us/graph/docs/concepts/known_issues#json-batching}
*
* @param {Map<string, BatchRequestStep>} requests - The map of requests.
* @returns The boolean indicating the validation status
*/
privatestaticvalidateDependencies(requests: Map<string,BatchRequestStep>): boolean{
constisParallel=(reqs: Map<string,BatchRequestStep>): boolean=>{
constiterator=reqs.entries();
letcur=iterator.next();
while(!cur.done){
constcurReq=cur.value[1];
if(curReq.dependsOn!==undefined&&curReq.dependsOn.length>0){
returnfalse;
}
cur=iterator.next();
}
returntrue;
};
constisSerial=(reqs: Map<string,BatchRequestStep>): boolean=>{
constiterator=reqs.entries();
letcur=iterator.next();
constfirstRequest: BatchRequestStep=cur.value[1];
if(firstRequest.dependsOn!==undefined&&firstRequest.dependsOn.length>0){
returnfalse;
}
letprev=cur;
cur=iterator.next();
while(!cur.done){
constcurReq: BatchRequestStep=cur.value[1];
if(curReq.dependsOn===undefined||curReq.dependsOn.length!==1||curReq.dependsOn[0]!==prev.value[1].id){
returnfalse;
}
prev=cur;
cur=iterator.next();
}
returntrue;
};
constisSame=(reqs: Map<string,BatchRequestStep>): boolean=>{
constiterator=reqs.entries();
letcur=iterator.next();
constfirstRequest: BatchRequestStep=cur.value[1];
letdependencyId: string;
if(firstRequest.dependsOn===undefined||firstRequest.dependsOn.length===0){
dependencyId=firstRequest.id;
}else{
if(firstRequest.dependsOn.length===1){
constfDependencyId=firstRequest.dependsOn[0];
if(fDependencyId!==firstRequest.id&&reqs.has(fDependencyId)){
dependencyId=fDependencyId;
}else{
returnfalse;
}
}else{
returnfalse;
}
}
cur=iterator.next();
while(!cur.done){
constcurReq=cur.value[1];
if((curReq.dependsOn===undefined||curReq.dependsOn.length===0)&&dependencyId!==curReq.id){
returnfalse;
}
if(curReq.dependsOn!==undefined&&curReq.dependsOn.length!==0){
if(curReq.dependsOn.length===1&&(curReq.id===dependencyId||curReq.dependsOn[0]!==dependencyId)){
returnfalse;
}
if(curReq.dependsOn.length>1){
returnfalse;
}
}
cur=iterator.next();
}
returntrue;
};
if(requests.size===0){
consterror=newError("Empty requests map, Please provide at least one request.");
error.name="Empty Requests Error";
throwerror;
}
returnisParallel(requests)||isSerial(requests)||isSame(requests);
}
/**
* @private
* @static
* @async
* Converts Request Object instance to a JSON
* @param {IsomorphicRequest} request - The IsomorphicRequest Object instance
* @returns A promise that resolves to JSON representation of a request
*/
privatestaticasyncgetRequestData(request: IsomorphicRequest): Promise<RequestData>{
constrequestData: RequestData={
url: "",
};
// Stripping off hostname, port and url scheme
requestData.url=request.url.replace(/^(?:http)?s?:?(?:\/\/)?[^/]+\/(?:v1.0|beta)?/i,"");// replaces <scheme>?<?>?<//><hostname:port>+</>?<version>+ by an empty string
requestData.method=request.method;
constheaders={};
request.headers.forEach((value,key)=>{
headers[key]=value;
});
if(Object.keys(headers).length){
requestData.headers=headers;
}
if(request.method===RequestMethod.PATCH||request.method===RequestMethod.POST||request.method===RequestMethod.PUT){
requestData.body=awaitBatchRequestContent.getRequestBody(request);
}
/**
* TODO: Check any other property needs to be used from the Request object and add them
*/
returnrequestData;
}
/**
* @private
* @static
* @async
* Gets the body of a Request object instance
* @param {IsomorphicRequest} request - The IsomorphicRequest object instance
* @returns The Promise that resolves to a body value of a Request
*/
privatestaticasyncgetRequestBody(request: IsomorphicRequest): Promise<any>{
letbodyParsed=false;
letbody;
try{
constcloneReq=request.clone();
body=awaitcloneReq.json();
bodyParsed=true;
}catch(e){
//TODO- Handle empty catches
}
if(!bodyParsed){
try{
if(typeofBlob!=="undefined"){
constblob=awaitrequest.blob();
constreader=newFileReader();
body=awaitnewPromise((resolve)=>{
reader.addEventListener(
"load",
()=>{
constdataURL=reader.resultasstring;
/**
* Some valid dataURL schemes:
* 1. data:text/vnd-example+xyz;foo=bar;base64,R0lGODdh
* 2. data:text/plain;charset=UTF-8;page=21,the%20data:1234,5678
* 3. data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
* 4. data:image/png,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
* 5. data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
* @see Syntax {@link https://en.wikipedia.org/wiki/Data_URI_scheme} for more
*/
constregex=newRegExp("^s*data:(.+?/.+?(;.+?=.+?)*)?(;base64)?,(.*)s*$");
constsegments=regex.exec(dataURL);
resolve(segments[4]);
},
false,
);
reader.readAsDataURL(blob);
});
}elseif(typeofBuffer!=="undefined"){
constbuffer=awaitrequest.buffer();
body=buffer.toString("base64");
}
bodyParsed=true;
}catch(e){
// TODO-Handle empty catches
}
}
returnbody;
}
/**
* @public
* @constructor
* Constructs a BatchRequestContent instance
* @param {BatchRequestStep[]} [requests] - Array of requests value
* @returns An instance of a BatchRequestContent
*/
publicconstructor(requests?: BatchRequestStep[]){
this.requests=newMap();
if(typeofrequests!=="undefined"){
constlimit=BatchRequestContent.requestLimit;
if(requests.length>limit){
consterror=newError(`Maximum requests limit exceeded, Max allowed number of requests are ${limit}`);
error.name="Limit Exceeded Error";
throwerror;
}
for(constreqofrequests){
this.addRequest(req);
}
}
}
/**
* @public
* Adds a request to the batch request content
* @param {BatchRequestStep} request - The request value
* @returns The id of the added request
*/
publicaddRequest(request: BatchRequestStep): string{
constlimit=BatchRequestContent.requestLimit;
if(request.id===""){
consterror=newError(`Id for a request is empty, Please provide an unique id`);
error.name="Empty Id For Request";
throwerror;
}
if(this.requests.size===limit){
consterror=newError(`Maximum requests limit exceeded, Max allowed number of requests are ${limit}`);
error.name="Limit Exceeded Error";
throwerror;
}
if(this.requests.has(request.id)){
consterror=newError(`Adding request with duplicate id ${request.id}, Make the id of the requests unique`);
error.name="Duplicate RequestId Error";
throwerror;
}
this.requests.set(request.id,request);
returnrequest.id;
}
/**
* @public
* Removes request from the batch payload and its dependencies from all dependents
* @param {string} requestId - The id of a request that needs to be removed
* @returns The boolean indicating removed status
*/
publicremoveRequest(requestId: string): boolean{
constdeleteStatus=this.requests.delete(requestId);
constiterator=this.requests.entries();
letcur=iterator.next();
/**
* Removing dependencies where this request is present as a dependency
*/
while(!cur.done){
constdependencies=cur.value[1].dependsOn;
if(typeofdependencies!=="undefined"){
constindex=dependencies.indexOf(requestId);
if(index!==-1){
dependencies.splice(index,1);
}
if(dependencies.length===0){
deletecur.value[1].dependsOn;
}
}
cur=iterator.next();
}
returndeleteStatus;
}
/**
* @public
* @async
* Serialize content from BatchRequestContent instance
* @returns The body content to make batch request
*/
publicasyncgetContent(): Promise<BatchRequestBody>{
constrequests: BatchRequestData[]=[];
constrequestBody: BatchRequestBody={
requests,
};
constiterator=this.requests.entries();
letcur=iterator.next();
if(cur.done){
consterror=newError("No requests added yet, Please add at least one request.");
error.name="Empty Payload";
throwerror;
}
if(!BatchRequestContent.validateDependencies(this.requests)){
consterror=newError(`Invalid dependency found, Dependency should be:
1. Parallel - no individual request states a dependency in the dependsOn property.
2. Serial - all individual requests depend on the previous individual request.
3. Same - all individual requests that state a dependency in the dependsOn property, state the same dependency.`);
error.name="Invalid Dependency";
throwerror;
}
while(!cur.done){
constrequestStep: BatchRequestStep=cur.value[1];
constbatchRequestData: BatchRequestData=(awaitBatchRequestContent.getRequestData(requestStep.requestasIsomorphicRequest))asBatchRequestData;
/**
* @see{@https://tools.ietf.org/html/rfc7578#section-4.4}
* TODO- Setting/Defaulting of content-type header to the correct value
* @see {@link https://developer.microsoft.com/en-us/graph/docs/concepts/json_batching#request-format}
*/
if(batchRequestData.body!==undefined&&(batchRequestData.headers===undefined||batchRequestData.headers["content-type"]===undefined)){
consterror=newError(`Content-type header is not mentioned for request #${requestStep.id}, For request having body, Content-type header should be mentioned`);
error.name="Invalid Content-type header";
throwerror;
}
batchRequestData.id=requestStep.id;
if(requestStep.dependsOn!==undefined&&requestStep.dependsOn.length>0){
batchRequestData.dependsOn=requestStep.dependsOn;
}
requests.push(batchRequestData);
cur=iterator.next();
}
requestBody.requests=requests;
returnrequestBody;
}
/**
* @public
* Adds a dependency for a given dependent request
* @param {string} dependentId - The id of the dependent request
* @param {string} [dependencyId] - The id of the dependency request, if not specified the preceding request will be considered as a dependency
* @returns Nothing
*/
publicaddDependency(dependentId: string,dependencyId?: string): void{
if(!this.requests.has(dependentId)){
consterror=newError(`Dependent ${dependentId} does not exists, Please check the id`);
error.name="Invalid Dependent";
throwerror;
}
if(typeofdependencyId!=="undefined"&&!this.requests.has(dependencyId)){
consterror=newError(`Dependency ${dependencyId} does not exists, Please check the id`);
error.name="Invalid Dependency";
throwerror;
}
if(typeofdependencyId!=="undefined"){
constdependent=this.requests.get(dependentId);
if(dependent.dependsOn===undefined){
dependent.dependsOn=[];
}
if(dependent.dependsOn.indexOf(dependencyId)!==-1){
consterror=newError(`Dependency ${dependencyId} is already added for the request ${dependentId}`);
error.name="Duplicate Dependency";
throwerror;
}
dependent.dependsOn.push(dependencyId);
}else{
constiterator=this.requests.entries();
letprev;
letcur=iterator.next();
while(!cur.done&&cur.value[1].id!==dependentId){
prev=cur;
cur=iterator.next();
}
if(typeofprev!=="undefined"){
constdId=prev.value[0];
if(cur.value[1].dependsOn===undefined){
cur.value[1].dependsOn=[];
}
if(cur.value[1].dependsOn.indexOf(dId)!==-1){
consterror=newError(`Dependency ${dId} is already added for the request ${dependentId}`);
error.name="Duplicate Dependency";
throwerror;
}
cur.value[1].dependsOn.push(dId);
}else{
consterror=newError(`Can't add dependency ${dependencyId}, There is only a dependent request in the batch`);
error.name="Invalid Dependency Addition";
throwerror;
}
}
}
/**
* @public
* Removes a dependency for a given dependent request id
* @param {string} dependentId - The id of the dependent request
* @param {string} [dependencyId] - The id of the dependency request, if not specified will remove all the dependencies of that request
* @returns The boolean indicating removed status
*/
publicremoveDependency(dependentId: string,dependencyId?: string): boolean{
constrequest=this.requests.get(dependentId);
if(typeofrequest==="undefined"||request.dependsOn===undefined||request.dependsOn.length===0){
returnfalse;
}
if(typeofdependencyId!=="undefined"){
constindex=request.dependsOn.indexOf(dependencyId);
if(index===-1){
returnfalse;
}
request.dependsOn.splice(index,1);
returntrue;
}else{
deleterequest.dependsOn;
returntrue;
}
}
}