Batching is a way of combining multiple requests to resources in same/different workloads in a single HTTP request. This can be achieved by making a post call with those requests as a JSON payload to $batch endpoint.
A component which eases the way of creating batch request payload. This class handles all the batch specific payload construction and stuffs, we just need to worry about individual requests.
A Component to simplify the processing of batch responses by providing functionalities like getResponses, getResponseById, getResponsesIterator
// elem here is the input HTML element of type fileconstserialBatching=asyncfunction(elem){try{letfile=elem.files[0];letuploadProfilePhotoRequest=newRequest("/me/photo/$value",{method: "PUT",headers: {"Content-type": file.type,},body: file,});letuploadProfilePhotoStep: BatchRequestStep={id: "1",request: uploadProfilePhotoRequest,};letdownloadProfilePhotoRequest=newRequest("/me/photo/$value",{method: "GET",});letdownloadId="2";letdownloadProfilePhotoStep: BatchRequestStep={id: downloadId,request: downloadProfilePhotoRequest,// Adding dependsOn makes this request wait until the dependency finishes// This download request waits until the upload request completesdependsOn: ["1"],};//Create instance by passing a batch request stepletbatchRequestContent=newMicrosoftGraph.BatchRequestContent([uploadProfilePhotoStep,downloadProfilePhotoStep]);//Extracting content from the instanceletcontent=awaitbatchRequestContent.getContent();//Making call to $batch end point with the extracted contentletresponse=awaitclient.api("/$batch").post(content);//Create instance with response from the batch requestletbatchResponseContent=newMicrosoftGraph.BatchResponseContent(response);//Getting response by idconsole.log(batchResponseContent.getResponseById(downloadId));//Getting all the responsesconsole.log(batchResponseContent.getResponses());}catch(error){console.error(error);}};
You should convert the downloaded photos through batching to a Base64 representation if you want to render these in a browser.
b64toBlob=async(b64Data: any,contentType: string,sliceSize?: number): Promise<Blob>=>{contentType=contentType||"image/png";sliceSize=sliceSize||512;letbyteCharacters: string=atob(b64Data);letbyteArrays=[];for(letoffset=0;offset<byteCharacters.length;offset+=sliceSize){letslice=byteCharacters.slice(offset,offset+sliceSize);letbyteNumbers=newArray(slice.length);for(leti=0;i<slice.length;i++){byteNumbers[i]=slice.charCodeAt(i);}letbyteArray=newUint8Array(byteNumbers);byteArrays.push(byteArray);}letblob=newBlob(byteArrays,{type: contentType});returnblob;};blobToBase64=(blob: Blob): Promise<string>=>{returnnewPromise((resolve,reject)=>{constreader=newFileReader();reader.onerror=reject;reader.onload=(_)=>{resolve(reader.resultasstring);};reader.readAsDataURL(blob);});};downloadPhotosBatching=async(client: Client)=>{try{letusers=["user1@contoso.com","user2@contoso.com"];// create batch request steps for the users specified aboveconstbatchRequestSteps: BatchRequestStep[]=users.map((userId)=>{constrequest: BatchRequestStep={id: userId,request: newRequest(`/users/${userId}/photo/$value`,{method: "GET",}),};returnrequest;});// initiate the batchrequest and execute the operationconstbatchRequestContent=newBatchRequestContent(batchRequestSteps);constcontent=awaitbatchRequestContent.getContent();constbatchResponse=newBatchResponseContent(awaitclient.api("/$batch").post(content));// example on how to retrieve the base64 representation of the downloaded image for the first userconstresponse=batchResponse.getResponseById(users[0]);if(response.ok){vardata=awaitresponse.text();constbinToBlob=awaitthis.b64toBlob(data,"img/jpg");// you can associate the base64 output to an src attribute of an <img> HTML tagconstbase64Result=awaitthis.blobToBase64(binToBlob);console.log(base64Result);}}catch(error){console.error(error);}};
constparallelBatching=asyncfunction(){try{letfileName="test.pdf";letoneDriveFileRequest=newRequest(`/me/drive/root:/${fileName}:/content`,{method: "GET",});letoneDriveFileStep: BatchRequestStep={id: "1",request: oneDriveFileRequest,};letfolderDetails={name: "Testing Batch",folder: {},};letcreateFolder=newRequest("/me/drive/root/children",{method: "POST",headers: {"Content-type": "application/json",},body: JSON.stringify(folderDetails),});letcreateFolderStep: BatchRequestStep={id: "2",request: createFolder,dependsOn: ["1"],};letmailsRequest=newRequest("/me/messages",{method: "GET",});letmailsRequestStep: BatchRequestStep={id: "3",request: mailsRequest,dependsOn: ["2"],};//Create instance by passing a batch request stepletbatchRequestContent=newMicrosoftGraph.BatchRequestContent();// Dynamically adding requests to the batch contentletfileDownloadId=batchRequestContent.addRequest(oneDriveFileStep);letcreateFolderId=batchRequestContent.addRequest(createFolderStep);letmailsId=batchRequestContent.addRequest(mailsRequestStep);// Dynamically removing unnecessary dependencies// NOTE: Passing second param empty removes all the dependencies for that requestbatchRequestContent.removeDependency("3","2");// Dynamically removing unnecessary request. Removing a request automatically removes the dependencies in relevant dependents// Here download file dependency is removed from the onedrive create folder requestbatchRequestContent.removeRequest(fileDownloadId);// Now no requests depends on anything so the request will be made parallel in the service end// Extracting content from the instanceletcontent=awaitbatchRequestContent.getContent();//Making call to $batch end point with the extracted contentletresponse=awaitclient.api("/$batch").post(content);//Create instance with response from the batch requestletbatchResponse=newMicrosoftGraph.BatchResponseContent(response);//Getting iterator and looping through the responses iteratorletiterator=batchResponse.getResponsesIterator();letdata=iterator.next();while(!data.done){console.log(data.value[0]+":"+data.value[1]);data=iterator.next();}}catch(error){console.error(error);}};
Create a folder in OneDrive and upload multiple files - Making batch request with all other request depend on one request
// elem here is the input HTML element of type fileconstsameBatching=asyncfunction(elem){try{letfile1=elem.files[0];letfile2=elem.files[1];letfolderDetails={name: "MyFiles",folder: {},};letcreateFolder=newRequest("/me/drive/root/children",{method: "POST",headers: {"Content-type": "application/json",},body: JSON.stringify(folderDetails),});letcreateFolderStep: BatchRequestStep={id: "1",request: createFolder,};letuploadFileRequest1=newRequest(`/me/drive/root:/MyFiles/${file1.name}:/content`,{method: "PUT",headers: {"Content-type": file1.type,},body: file1,});letuploadFileStep1: BatchRequestStep={id: "2",request: uploadFileRequest1,dependsOn: ["1"],};letuploadFileRequest2=newRequest(`/me/drive/root:/MyFiles/${file2.name}:/content`,{method: "PUT",headers: {"Content-type": file2.type,},body: file2,});letuploadFileStep2: BatchRequestStep={id: "3",request: uploadFileRequest2,dependsOn: ["1"],};letbatchRequestContent=newMicrosoftGraph.BatchRequestContent([createFolderStep,uploadFileStep1,uploadFileStep2]);letcontent=awaitbatchRequestContent.getContent();letresponse=awaitclient.api("/$batch").post(content);letbatchResponseContent=newMicrosoftGraph.BatchResponseContent(response);console.log(batchResponseContent.getResponses());}catch(error){console.error(error);}};
Refer, JSON Batching, Known Issues documents for current constraints in the batching