### Install Development Dependencies Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/CONTRIBUTING.md Run this command to install all necessary dependencies for local development. ```cmd npm install ``` -------------------------------- ### Install isomorphic-fetch for Node.js Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/wiki/Migration-from-1.x.x-to-2.x.x When using the SDK in a Node.js environment, install 'isomorphic-fetch' to polyfill the fetch API if your Node version does not support it natively. ```cmd npm i -S "isomorphic-fetch"; ``` -------------------------------- ### Install Microsoft Graph JavaScript Core SDK Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/design/kiota-e2e.md Install the core library and types for the Microsoft Graph JavaScript SDK using npm. ```Shell npm install @microsoft/msgraph-sdk-javascript-core --save npm install @microsoft/msgraph-sdk-javascript-types --save-dev ``` -------------------------------- ### Initialize MSALAuthenticationProvider (v1.x.x) Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/wiki/Migration-from-1.x.x-to-2.x.x Example of initializing MSALAuthenticationProvider with client ID, scopes, and redirect URI in version 1.x.x. ```typescript const clientID = "your_client_id"; // Client Id of the registered application const graphScopes = ["user.read", "mail.send"]; // An array of graph scopes const options = { redirectUri: "Your redirect URI", }; const authProvider = new MicrosoftGraph.MSALAuthenticationProvider(clientId, graphScopes, options); ``` -------------------------------- ### Initialize MSALAuthenticationProvider with UserAgentApplication (v1.x.x) Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/wiki/Migration-from-1.x.x-to-2.x.x Example of initializing MSALAuthenticationProvider using an existing UserAgentApplication instance in version 1.x.x. ```typescript const clientId = "your_client_id"; // Client Id of the registered application const callback = (errorDesc, token, error, tokenType) => {}; const options = { redirectUri: "Your redirect URI", }; const graphScopes = ["user.read", "mail.send"]; // An array of graph scopes const userAgentApplication = new Msal.UserAgentApplication(clientId, undefined, callback, options); const authProvider = new MicrosoftGraph.MSALAuthenticationProvider(userAgentApplication, graphScopes); ``` -------------------------------- ### Initialize MSALAuthenticationProvider with UserAgentApplication and imports (v1.x.x) Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/wiki/Migration-from-1.x.x-to-2.x.x Example of initializing MSALAuthenticationProvider with UserAgentApplication and specific imports in version 1.x.x. ```typescript import { UserAgentApplication } from "msal"; import { MSALAuthenticationProvider } from "./node_modules/@microsoft/microsoft-graph-client/lib/src/MSALAuthenticationProvider"; const clientId = "your_client_id"; // Client Id of the registered application const callback = (errorDesc, token, error, tokenType) => {}; const options = { redirectUri: "Your redirect URI", }; const graphScopes = ["user.read", "mail.send"]; // An array of graph scopes const userAgentApplication = new UserAgentApplication(clientId, undefined, callback, options); const authProvider = new MSALAuthenticationProvider(userAgentApplication, scopes); ``` -------------------------------- ### Initialize AuthCodeMSALBrowserAuthenticationProvider (npm) Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/AuthCodeMSALBrowserAuthenticationProvider.md Initialize the AuthCodeMSALBrowserAuthenticationProvider using npm. Ensure you have installed the necessary packages and initialized the MSAL PublicClientApplication instance. ```typescript import { PublicClientApplication, InteractionType, AccountInfo } from "@azure/msal-browser"; import { AuthCodeMSALBrowserAuthenticationProvider, AuthCodeMSALBrowserAuthenticationProviderOptions } from "@microsoft/microsoft-graph-client/authProviders/authCodeMsalBrowser"; import { Client } from "@microsoft/microsoft-graph-client"; const options: AuthCodeMSALBrowserAuthenticationProviderOptions = { account: account, // the AccountInfo instance to acquire the token for. interactionType: InteractionType.Popup, // msal-browser InteractionType scopes: ["user.read", "mail.send"] // example of the scopes to be passed }; // Pass the PublicClientApplication instance from step 2 to create AuthCodeMSALBrowserAuthenticationProvider instance const authProvider = new AuthCodeMSALBrowserAuthenticationProvider(publicClientApplication, options); // Initialize the Graph client const graphClient = Client.initWithMiddleware({ authProvider }); ``` -------------------------------- ### Install Microsoft Graph Client via npm Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/README.md Use this command to install the Microsoft Graph JavaScript client library using npm. Ensure you have Node.js 12 LTS or higher. ```cmd npm install @microsoft/microsoft-graph-client ``` -------------------------------- ### Initialize MSALAuthenticationProvider with imports (v1.x.x) Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/wiki/Migration-from-1.x.x-to-2.x.x Example of initializing MSALAuthenticationProvider with explicit imports in version 1.x.x. ```typescript import { MSALAuthenticationProvider } from "./node_modules/@microsoft/microsoft-graph-client/lib/src/MSALAuthenticationProvider"; const clientId = "your_client_id"; // Client Id of the registered application const graphScopes = ["user.read", "mail.send"]; // An array of graph scopes const options = { redirectUri: "Your redirect URI", }; const authProvider = new MSALAuthenticationProvider(clientId, scopes, options); ``` -------------------------------- ### Install Microsoft Graph Javascript Service Library Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/design/kiota-e2e.md Use npm to install the Microsoft Graph Javascript Service Library for v1.0 endpoints. Ensure you have npm installed and configured. ```shell npm install @microsoft/msgraph-sdk-javascript --save ``` -------------------------------- ### Download Multiple Photos and Convert to Base64 with Batching Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/content/Batching.md This example shows how to download multiple user profile photos using batching and then convert them to a Base64 representation for browser rendering. Helper functions `b64toBlob` and `blobToBase64` are included for the conversion process. ```typescript b64toBlob = async (b64Data: any, contentType: string, sliceSize?: number): Promise => { contentType = contentType || "image/png"; sliceSize = sliceSize || 512; let byteCharacters: string = atob(b64Data); let byteArrays = []; for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) { let slice = byteCharacters.slice(offset, offset + sliceSize); let byteNumbers = new Array(slice.length); for (let i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } let byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } let blob = new Blob(byteArrays, { type: contentType }); return blob; }; blobToBase64 = (blob: Blob): Promise => { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onerror = reject; reader.onload = (_) => { resolve(reader.result as string); }; reader.readAsDataURL(blob); }); }; downloadPhotosBatching = async (client: Client) => { try { let users = ["user1@contoso.com", "user2@contoso.com"]; // create batch request steps for the users specified above const batchRequestSteps: BatchRequestStep[] = users.map((userId) => { const request: BatchRequestStep = { id: userId, request: new Request(`/users/${userId}/photo/$value`, { method: "GET", }), }; return request; }); // initiate the batchrequest and execute the operation const batchRequestContent = new BatchRequestContent(batchRequestSteps); const content = await batchRequestContent.getContent(); const batchResponse = new BatchResponseContent(await client.api("/$batch").post(content)); // example on how to retrieve the base64 representation of the downloaded image for the first user const response = batchResponse.getResponseById(users[0]); if (response.ok) { var data = await response.text(); const binToBlob = await this.b64toBlob(data, "img/jpg"); // you can associate the base64 output to an src attribute of an HTML tag const base64Result = await this.blobToBase64(binToBlob); console.log(base64Result); } } catch (error) { console.error(error); } }; ``` -------------------------------- ### Call Microsoft Graph API with Core SDK Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/design/kiota-e2e.md Demonstrates making calls to get user information and send an email using the initialized Graph client. ```TypeScript const me: User = await getMe(); await sendMail(); async function getMe(): Promise { return await graphClient.api("/me").get(); } async function sendMail(): Promise { const message: Message = { subject: "Hello Graph TypeScript SDK!", body: { contentType: BodyType.Html, content: "Hello Graph TypeScript SDK!", }, toRecipients: [ { emailAddress: { address: "admin@m365x263716.onmicrosoft.com", }, }, ], }; return await client.api("/me/sendMail").post({ message: message, }); } ``` -------------------------------- ### Initialize Client and Use Chaos Handler in Manual Mode Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/ChaosHandlerSamples.md Initializes the Microsoft Graph client and demonstrates how to configure and use the Chaos Handler in manual mode with a predefined map for response codes. This example sends an email and expects potential errors based on the manual map. ```javascript require("isomorphic-fetch"); const MicrosoftGraph = require("../../lib/src/index.js"); const secrets = require("./secrets"); const fs = require("fs"); // Initialising the client const client = MicrosoftGraph.Client.init({ defaultVersion: "v1.0", debugLogging: true, authProvider: (done) => { done(null, secrets.accessToken); }, }); /* Create a custom MiddlewareChain passing information in this way const manualMap = new Map([["/me/messages/.*", new Map([["GET", 429], ["PATCH", 429]])], ["/me", new Map([["POST", 502]])]]); const chaosHandler = new MicrosoftGraph.ChaosHandler(new MicrosoftGraph.ChaosHandlerOptions(MicrosoftGraph.ChaosStrategy.MANUAL), manualMap); */ // This request would use the Map (Manual mode) const mail = { subject: "Chaos Handler Samples", toRecipients: [ { emailAddress: { address: "admin@M365x003297.OnMicrosoft.com", }, }, ], body: { content: "

Testing Handler Samples Sample


https://github.com/microsoftgraph/msgraph-sdk-javascript", contentType: "html", }, }; client .api("/users/me/sendMail") .post({ message: mail, }) .then((res) => { console.log(res, "This is for sendMail"); }) .catch((err) => { console.log(err, "This is for sendMail in error case"); }); ``` -------------------------------- ### Update and Download Profile Photo Serially with Batching Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/content/Batching.md This example demonstrates how to update a user's profile photo and then immediately download it within the same batch request. It uses `dependsOn` to ensure the download request waits for the upload to complete. ```typescript const serialBatching = async function(elem) { try { let file = elem.files[0]; let uploadProfilePhotoRequest = new Request("/me/photo/$value", { method: "PUT", headers: { "Content-type": file.type, }, body: file, }); let uploadProfilePhotoStep: BatchRequestStep = { id: "1", request: uploadProfilePhotoRequest, }; let downloadProfilePhotoRequest = new Request("/me/photo/$value", { method: "GET", }); let downloadId = "2"; let downloadProfilePhotoStep: BatchRequestStep = { id: downloadId, request: downloadProfilePhotoRequest, // Adding dependsOn makes this request wait until the dependency finishes // This download request waits until the upload request completes dependsOn: ["1"], }; //Create instance by passing a batch request step let batchRequestContent = new MicrosoftGraph.BatchRequestContent([uploadProfilePhotoStep, downloadProfilePhotoStep]); //Extracting content from the instance let content = await batchRequestContent.getContent(); //Making call to $batch end point with the extracted content let response = await client.api("/$batch").post(content); //Create instance with response from the batch request let batchResponseContent = new MicrosoftGraph.BatchResponseContent(response); //Getting response by id console.log(batchResponseContent.getResponseById(downloadId)); //Getting all the responses console.log(batchResponseContent.getResponses()); } catch (error) { console.error(error); } }; ``` -------------------------------- ### Creating a Custom Middleware Chain Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/CustomMiddlewareChain.md Construct a middleware chain by sequentially linking custom and library-provided middleware using the `setNext()` method. This example chains an authentication handler, a custom logging handler, and a custom HTTP message handler. ```typescript import { ImplicitMSALAuthenticationProvider } from "@microsoft/microsoft-graph-client"; import { MyLoggingHandler } from "./MyLoggingHandler"; import { MyHttpMessageHandler } from "./MyHttpMessageHandler"; let authProvider = new ImplicitMSALAuthenticationProvider("", ["user.read"]); let authenticationHandler = new AuthenticationHandler(authProvider); let myLoggingHandler = new MyLoggingHandler(); let myHttpMessageHandler = new MyHttpMessageHandler(); // Note: myHttpMessageHandler is the last in the chain so there is no need of setting next middleware for it. authenticationHandler.setNext(myLoggingHandler); myLoggingHandler.setNext(myHttpMessageHandler); ``` -------------------------------- ### Create TokenCredentialAuthenticationProvider with ClientSecretCredential (TypeScript) Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/TokenCredentialAuthenticationProvider.md Demonstrates how to create a ClientSecretCredential and use it with TokenCredentialAuthenticationProvider to initialize the Microsoft Graph client in a TypeScript Node.js application. Ensure you have the necessary @azure/identity and @microsoft/microsoft-graph-client packages installed. ```typescript // Import the TokenCredential class that you wish to use. This example uses a Client SecretCredential import { ClientSecretCredential } from "@azure/identity"; import { Client } from "@microsoft/microsoft-graph-client"; import { TokenCredentialAuthenticationProvider, TokenCredentialAuthenticationProviderOptions } from "@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials"; // Create an instance of the TokenCredential class that is imported const tokenCredential = new ClientSecretCredential("your_tenantId", "your_clientId", "your_clientSecret"); // Set your scopes and options for TokenCredential.getToken (Check the ` interface GetTokenOptions` in (TokenCredential Implementation)[https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/core/core-auth/src/tokenCredential.ts]) const options: TokenCredentialAuthenticationProviderOptions = { scopes: [scopes], getTokenOptions }; // Create an instance of the TokenCredentialAuthenticationProvider by passing the tokenCredential instance and options to the constructor const authProvider = new TokenCredentialAuthenticationProvider(tokenCredential, options); const client = Client.initWithMiddleware({ debugLogging: true, authProvider: authProvider, }); const res = await client.api("/users/").get(); ``` -------------------------------- ### Custom Logging Middleware Implementation Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/CustomMiddlewareChain.md Implement a custom middleware handler that accesses and uses `middlewareOptions` from the context. This example logs the request URL with a custom prefix if provided. ```typescript // MyLoggingHandler.ts import { Middleware } from "@microsoft/microsoft-graph-client"; import { Context } from "@microsoft/microsoft-graph-client"; export class MyLoggingHandler implements Middleware { private nextMiddleware: Middleware; public async execute(context: Context): Promise { try { let url: string; if (typeof context.request === "string") { url = context.request; } else { url = context.request.url; } if (context.middlewareOptions !== undefined && context.middlewareOptions.loggingPrefix !== undefined) { console.log(`${context.middlewareOptions.loggingPrefix}: ${url}`); } else { console.log(url); } await this.nextMiddleware.execute(context); } catch (error) { throw error; } } public setNext(next: Middleware): void { this.nextMiddleware = next; } } ``` -------------------------------- ### Get User Details Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/README.md Retrieves details for the authenticated user. Ensure you have an authenticated client instance before calling this. ```typescript try { let userDetails = await client.api("/me").get(); console.log(userDetails); } catch (error) { throw error; } ``` -------------------------------- ### GET Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/Actions.md Retrieve information from the Microsoft Graph API using the .get() method. This is typically used for fetching resource details. ```APIDOC ## GET ### Description Retrieve information from the graph using `.get()`. ### Method GET ### Endpoint `/me` ### Request Example ```typescript try { let res = await client.api("/me").get(); console.log(res); } catch (error) { throw error; } ``` ``` -------------------------------- ### Download File with GETSTREAM Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/Actions.md Utilize .getStream() for downloading files, particularly large ones, using NodeJS streams. This example shows downloading a file from OneDrive. Ensure file paths are correctly specified. ```typescript const fs = require("fs"); client .api("/me/drive/root/children//content") .getStream() //Eg: test.pdf .then((stream) => { let writeStream = fs.createWriteStream(`../`); // Eg: test.pdf stream.pipe(writeStream).on("error", (err) => { throw err; }); writeStream.on("finish", () => { console.log("Downloaded"); }); writeStream.on("error", (err) => { throw err; }); }) .catch((error) => { throw error; }); ``` -------------------------------- ### Update Profile Picture with PUT Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/Actions.md The .put() method is used to replace a resource. This example shows updating a user's profile picture from a file object obtained from an HTML input form. Ensure the file object is correctly retrieved. ```typescript let file; // FileObject retrieved from the HTML input type=file try { let res = await client.api("/me/photo/$value").put(file); console.log(res); } catch (error) { throw error; } ``` -------------------------------- ### Use Chaos Handler in Random Mode Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/ChaosHandlerSamples.md Configures the Chaos Handler to operate in random mode with a specified error generation percentage. This example makes a GET request to '/me' and may receive simulated errors. ```javascript // OverRiding to Random mode, providing the chaos percentage as 60(percentage times the error would be generated from handler) client .api("/me") .middlewareOptions([new MicrosoftGraph.ChaosHandlerOptions(MicrosoftGraph.ChaosStrategy.RANDOM, "I generated the error", undefined, 60)]) .get() .then((res) => { console.log(res); }) .catch((err) => { console.log(err); }); ``` -------------------------------- ### Build Project Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/CONTRIBUTING.md Execute this command to build the project after making changes. ```cmd npm run build ``` -------------------------------- ### Get Raw Response using Async/Await Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/GettingRawResponse.md Use `responseType(ResponseType.RAW)` to get the raw Response object when using async/await. This allows direct access to the response. ```typescript const rawResponse = await client .api("/me") .select("displayName") .responseType(ResponseType.RAW) .get(); console.log(rawResponse); ``` -------------------------------- ### Run Linting Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/CONTRIBUTING.md Execute this command to check for code style and quality issues. ```cmd npm run lint ``` -------------------------------- ### Retrieve Raw HTTP Response Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/wiki/Migration-from-1.x.x-to-2.x.x To get the raw HTTP response, use the `.responseType(ResponseType.RAW)` method before making the GET request. The callback signature changes to accept only the error and the raw response. ```typescript client .api('/me') .get((err, res, rawResponse) => { console.log(rawResponse); }); ``` ```typescript client .api('/me') .responseType(ResponseType.RAW) .get((err, rawResponse) => { console.log(rawResponse); }); ``` -------------------------------- ### Initializing Client with Middleware Options Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/CustomMiddlewareChain.md Pass custom options to the client during initialization. These options will be available in the middleware's context. ```typescript let clientOptions: ClientOptions = { middleware: authenticationHandler, middlewareOptions: { loggingPrefix: "MSGraph-Client-Library", }, }; ``` -------------------------------- ### Initialize Client with Options and AuthProvider Function Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/CreatingClientInstance.md Initialize the client by providing a custom authProvider function directly in the Options object. This function is responsible for obtaining and refreshing the access token, and must call back with the token or an error. ```typescript // Some callback function const authProvider: AuthProvider = (callback: AuthProviderCallback) => { // Your logic for getting and refreshing accessToken // Error should be passed in case of error while authenticating // accessToken should be passed upon successful authentication callback(error, accessToken); }; let options: Options = { authProvider, }; const client = Client.init(options); ``` -------------------------------- ### Initialize Client with Default Middleware Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/CreatingClientInstance.md Use this method to create a client instance with the default middleware chain. Pass an instance of a class implementing the AuthenticationProvider interface to the authProvider option. ```typescript let clientOptions: ClientOptions = { authProvider: new YourAuthProviderClass(), }; const client = Client.initWithMiddleware(clientOptions); ``` -------------------------------- ### Specify Browser Entry Point in package.json Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/design/publishing.md Use the 'browser' field in package.json to indicate the browser-specific entry point for the SDK. This helps bundlers resolve the correct file for browser environments. ```json "browser": { "lib/es/src/index.js": "lib/es/src/browser/index.js" } ``` -------------------------------- ### Run Tests Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/CONTRIBUTING.md Use this command to run the project's test suite to validate your changes. ```cmd npm run test ``` -------------------------------- ### Get Large File Upload Session Information Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/tasks/LargeFileUploadTask.md Retrieve the details of a large file upload session. This includes the session URL, expiry date, and cancellation status. ```typescript const uploadsession: LargeFileUploadSession = uploadTask.getUploadSession(); ``` -------------------------------- ### Get Raw Response using Callback Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/GettingRawResponse.md Use `responseType(ResponseType.RAW)` with the callback method to retrieve the raw Response object. The callback receives the raw response as the second argument. ```typescript client .api("/me") .select("displayName") .responseType(ResponseType.RAW) .get((error, rawResponse) => { console.log(rawResponse); }); ``` -------------------------------- ### Initialize TokenCredentialAuthenticationProvider in Browser (HTML) Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/TokenCredentialAuthenticationProvider.md Illustrates how to include and use the TokenCredentialAuthenticationProvider in a browser environment by referencing the bundled JavaScript file. This method is suitable for client-side applications where the SDK is loaded via a script tag. ```html ; // create an authProvider var authProvider = new MicrosoftGraphTokenCredentialAuthProvider.TokenCredentialAuthenticationProvider(tokenCred, { scopes: scopes }); client = MicrosoftGraph.Client.initWithMiddleware({ authProvider: authProvider, }); ``` -------------------------------- ### Delete OneDrive File with DELETE Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/Actions.md Use the .delete() method to remove a resource from the graph. This example shows deleting a file from OneDrive. Ensure the correct file ID is provided. ```typescript try { let res = await client.api(`/me/drive/items/${ONE_DRIVE_FILE_ID_TO_DELETE}`).delete(); console.log(res); } catch (error) { console.error(error); } ``` -------------------------------- ### Calling Microsoft Graph with Fluent API and Raw API Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/design/kiota-e2e.md Demonstrates how to fetch user information and send emails using both the fluent API and the raw .api() method for migration flexibility. Ensure the graphClient and client are properly initialized before use. ```typescript const me: User | undefined = await getMe(); const meRaw: User | undefined = await getMeRaw(); await sendMail(); await sendMailRaw(); // The types returned by the fluent API should be the same as the .api() area. It should also be the same (or at least very similar) as the current @microsoft/microsoft-graph-types to offer seamless migration. async function getMe(): Promise { return await graphClient.me.get(); } // Allowing raw calls (using the .api() method instead of the full fluent API) is important for migration purposes and cases we don't know the resource beforehands (thinking Graph Explorer, mgt-get, etc.) async function getMeRaw(): Promise { return await graphClient.api("/me").get(); } // Sending an email via the fluent API async function sendMail(): Promise { const message: Message = { subject: "Hello Graph TypeScript SDK!", body: { contentType: BodyType.Html, content: "Hello Graph TypeScript SDK!", }, toRecipients: [ { emailAddress: { address: "admin@m365x263716.onmicrosoft.com", }, }, ], }; return await client.me.sendMail.post(message); } // Sending the email via the .api() method async function sendMailRaw(): Promise { const message: Message = { subject: "Hello Graph TypeScript SDK!", body: { contentType: BodyType.Html, content: "Hello Graph TypeScript SDK!", }, toRecipients: [ { emailAddress: { address: "admin@m365x263716.onmicrosoft.com", }, }, ], }; return await client.api("/me/sendMail").post({ message: message, }); } ``` -------------------------------- ### Update Contact Birthday with PATCH Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/Actions.md Employ the .patch() method to partially update a resource. This example demonstrates updating a contact's birthday. Provide the contact ID and the fields to update. ```typescript let contactId = ""; let contactInfo = { birthday: "1991-07-22", }; try { let res = await client.api(`/me/contacts/${contactId}`).patch(contactInfo); console.log(res); } catch (error) { console.error(error); } ``` -------------------------------- ### Making parallel requests with dynamic dependency management Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/content/Batching.md Demonstrates creating a batch request with multiple steps, dynamically adding them, and then removing dependencies to ensure they are processed in parallel. This is useful when requests do not rely on each other's results. ```typescript const parallelBatching = async function() { try { let fileName = "test.pdf"; let oneDriveFileRequest = new Request(`/me/drive/root:/${fileName}:/content`, { method: "GET", }); let oneDriveFileStep: BatchRequestStep = { id: "1", request: oneDriveFileRequest, }; let folderDetails = { name: "Testing Batch", folder: {}, }; let createFolder = new Request("/me/drive/root/children", { method: "POST", headers: { "Content-type": "application/json", }, body: JSON.stringify(folderDetails), }); let createFolderStep: BatchRequestStep = { id: "2", request: createFolder, dependsOn: ["1"], }; let mailsRequest = new Request("/me/messages", { method: "GET", }); let mailsRequestStep: BatchRequestStep = { id: "3", request: mailsRequest, dependsOn: ["2"], }; //Create instance by passing a batch request step let batchRequestContent = new MicrosoftGraph.BatchRequestContent(); // Dynamically adding requests to the batch content let fileDownloadId = batchRequestContent.addRequest(oneDriveFileStep); let createFolderId = batchRequestContent.addRequest(createFolderStep); let mailsId = batchRequestContent.addRequest(mailsRequestStep); // Dynamically removing unnecessary dependencies // NOTE: Passing second param empty removes all the dependencies for that request batchRequestContent.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 request batchRequestContent.removeRequest(fileDownloadId); // Now no requests depends on anything so the request will be made parallel in the service end // Extracting content from the instance let content = await batchRequestContent.getContent(); //Making call to $batch end point with the extracted content let response = await client.api("/$").post(content); //Create instance with response from the batch request let batchResponse = new MicrosoftGraph.BatchResponseContent(response); //Getting iterator and looping through the responses iterator let iterator = batchResponse.getResponsesIterator(); let data = iterator.next(); while (!data.done) { console.log(data.value[0] + ":" + data.value[1]); data = iterator.next(); } } catch (error) { console.error(error); } }; ``` -------------------------------- ### Initialize Client with Custom Authentication Provider Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/CreatingClientInstance.md Instantiate the client with a custom authentication provider that implements the IAuthenticationProvider interface. This allows integration with any authentication library. ```typescript let clientOptions: ClientOptions = { // MyCustomAuthenticationProvider is the user's own authentication provider implementing AuthenticationProvider interface authProvider: new MyCustomAuthenticationProvider(), }; const client = Client.initWithMiddleware(clientOptions); ``` -------------------------------- ### Create TokenCredentialAuthenticationProvider with ClientSecretCredential (JavaScript) Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/TokenCredentialAuthenticationProvider.md Shows how to initialize the Microsoft Graph client using ClientSecretCredential and TokenCredentialAuthenticationProvider in a JavaScript Node.js application. This requires the @azure/identity and @microsoft/microsoft-graph-client packages. ```javascript // Import the TokenCredential class that you wish to use. This examples uses a ClientSecretCredential const { ClientSecretCredential } = require("@azure/identity"); const { Client } = require("@microsoft/microsoft-graph-client"); const { TokenCredentialAuthenticationProvider } = require("@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials"); // Create an instance of the TokenCredential class that is imported const credential = new ClientSecretCredential(tenantId, clientId, clientSecret); // Set your scopes and options for TokenCredential.getToken (Check the ` interface GetTokenOptions` in (TokenCredential Implementation)[https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/core/core-auth/src/tokenCredential.ts]) const authProvider = new TokenCredentialAuthenticationProvider(credential, { scopes: [scopes] }); const client = Client.initWithMiddleware({ debugLogging: true, authProvider, }); const res = await client.api("/users/").get(); ``` -------------------------------- ### Upload File with PUTSTREAM Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/Actions.md Use .putStream() for uploading files using NodeJS streams. This example demonstrates uploading a file to OneDrive. Ensure the local file path and the target file name in OneDrive are correctly specified. ```typescript let fs = require("fs"); try { let stream = fs.createReadStream(""); // Eg: "./test.jpg" let res = await client.api(`/me/drive/root/children//content`); // Eg: /me/drive/root/children/test.jpg/content console.log(res); } catch (error) { throw error; } ``` -------------------------------- ### Initialize Client with Custom Middleware Chain Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/CreatingClientInstance.md Configure a custom middleware chain by passing the first middleware instance to the middleware option in ClientOptions. This allows for customized request handling behavior. ```typescript let clientOptions: ClientOptions = { // MyFirstMiddleware is the first middleware in my custom middleware chain middleware: new MyFirstMiddleware(), }; const client = Client.initWithMiddleware(clientOptions); ``` -------------------------------- ### Initialize Microsoft Graph Client with Custom AuthenticationProvider Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/CustomAuthenticationProvider.md Instantiate your custom `MyAuthenticationProvider` and pass it to the `ClientOptions` when initializing the Microsoft Graph client. This ensures all requests use your custom authentication logic. ```typescript import { MyAuthenticationProvider } from "./MyAuthenticationProvider"; let clientOptions: ClientOptions = { authProvider: new MyAuthenticationProvider(), }; const client = Client.initWithMiddleware(clientOptions); ``` -------------------------------- ### OPTION AND OPTIONS Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/OtherAPIs.md Add request options using `.option()` for a single option or `.options()` for a dictionary of options. These options can be specific to Node.js environments or follow the Fetch standard. ```APIDOC ## OPTION AND OPTIONS You can pass in additional request options through `.option()` and `.options()`, either individually or in a dictionary. Options can be [node specific](https://github.com/bitinn/node-fetch#options) or [from fetch standard](https://fetch.spec.whatwg.org/#requestinit) ```typescript let HttpProxyAgent = require('https-proxy-agent'); try { // HTTP/HTTPS proxy to connect to let proxy = ; let agent = new HttpProxyAgent(proxy); // Below two statements are same let res1 = await client.api("/me").option("agent", agent).get(); let res2 = await client.api("/me").options({agent: agent}).get(); } catch (error) { throw error; } ``` ``` -------------------------------- ### Use Chaos Handler with Regex Matching Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/ChaosHandlerSamples.md Applies the Chaos Handler using a regular expression to match a specific message ID for an update request. This example attempts to update a birthday and may trigger a simulated error based on the regex rule. ```javascript // Using Manual Map with regex matching client .api("/me/messages/hjdlfslod-fdssdkjfs-6zdkmghs-sadhsu2") .header("content-type", "application/json") .update({ birthday: "1908-12-22T00:00:00Z", }) .then((res) => { console.log("This is regex matching... Updated Bday"); }) .catch((err) => { console.log(err, "matched"); }); ``` -------------------------------- ### Creating a folder and uploading files with dependent requests Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/content/Batching.md Illustrates creating a batch request where multiple file uploads depend on a folder creation step. This ensures files are uploaded only after the target folder exists. ```typescript // elem here is the input HTML element of type file const sameBatching = async function(elem) { try { let file1 = elem.files[0]; let file2 = elem.files[1]; let folderDetails = { name: "MyFiles", folder: {}, }; let createFolder = new Request("/me/drive/root/children", { method: "POST", headers: { "Content-type": "application/json", }, body: JSON.stringify(folderDetails), }); let createFolderStep: BatchRequestStep = { id: "1", request: createFolder, }; let uploadFileRequest1 = new Request(`/me/drive/root:/MyFiles/${file1.name}:/content`, { method: "PUT", headers: { "Content-type": file1.type, }, body: file1, }); let uploadFileStep1: BatchRequestStep = { id: "2", request: uploadFileRequest1, dependsOn: ["1"], }; let uploadFileRequest2 = new Request(`/me/drive/root:/MyFiles/${file2.name}:/content`, { method: "PUT", headers: { "Content-type": file2.type, }, body: file2, }); let uploadFileStep2: BatchRequestStep = { id: "3", request: uploadFileRequest2, dependsOn: ["1"], }; let batchRequestContent = new MicrosoftGraph.BatchRequestContent([createFolderStep, uploadFileStep1, uploadFileStep2]); let content = await batchRequestContent.getContent(); let response = await client.api("/$").post(content); let batchResponseContent = new MicrosoftGraph.BatchResponseContent(response); console.log(batchResponseContent.getResponses()); } catch (error) { console.error(error); } }; ``` -------------------------------- ### Configure Graph Javascript Service Library Client Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/design/kiota-e2e.md Initialize the Graph client using DeviceCodeCredential from Azure Identity for authentication. Ensure the correct tenant ID, client ID, and scopes are provided. ```typescript const deviceCodeCredentials = new DeviceCodeCredential({ tenantId: "b61f9af1-d6cf-4cc0-a6f6-befb38bc00ed", clientId: "bde251a6-0ef9-42a8-a40b-9ad9bb594b2c", }); const scopes = ["User.Read", "Mail.Send"]; const graphClient = Client.init({ authenticationTokenProvider: new AzureIdentityAuthenticationProvider(deviceCodeCredentials, scopes), }); ``` -------------------------------- ### Import ImplicitMSALAuthenticationProvider from @microsoft/microsoft-graph-client/authProviders/msal Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/wiki/Microsoft-Graph-JavaScript-SDK-V3.0-Upgrade-Guide Demonstrates an alternative way to import ImplicitMSALAuthenticationProvider for use with the Microsoft Graph JS SDK. ```javascript import { ImplicitMSALAuthenticationProvider } from "@microsoft/microsoft-graph-client/authProviders/msal"; ``` -------------------------------- ### Migrate to ImplicitMSALAuthenticationProvider with imports (v2.x.x) Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/wiki/Migration-from-1.x.x-to-2.x.x Updated initialization for MSAL authentication provider using ImplicitMSALAuthenticationProvider, msalConfig, and MSALAuthenticationProviderOptions with explicit imports in version 2.x.x. ```typescript import { UserAgentApplication } from "msal"; import { ImplicitMSALAuthenticationProvider } from "./node_modules/@microsoft/microsoft-graph-client/lib/src/ImplicitMSALAuthenticationProvider"; const msalConfig = { auth: { clientId: "your_client_id"; // Client Id of the registered application redirectUri: "your_redirect_uri", }, }; const graphScopes = ["user.read", "mail.send"]; // An array of graph scopes const msalInstance = new UserAgentApplication(msalConfig); const options = new MicrosoftGraph.MSALAuthenticationProviderOptions(graphScopes); const authProvider = new ImplicitMSALAuthenticationProvider(msalInstance, options); ``` -------------------------------- ### Add Request Options with .option() or .options() Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/OtherAPIs.md Provide additional request options, such as proxy agents, using `.option()` for a single option or `.options()` for a dictionary of options. These align with fetch standard options. ```javascript let HttpProxyAgent = require('https-proxy-agent'); try { // HTTP/HTTPS proxy to connect to let proxy = ; let agent = new HttpProxyAgent(proxy); // Below two statements are same let res1 = await client.api("/me").option("agent", agent).get(); let res2 = await client.api("/me").options({agent: agent}).get(); } catch (error) { throw error; } ``` -------------------------------- ### Initializing the Microsoft Graph Client with Middleware Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/CustomMiddlewareChain.md Initialize the Microsoft Graph client by passing the first middleware of your custom chain to the `ClientOptions`. This configures the client to use your defined middleware pipeline for requests. ```typescript let clientOptions: ClientOptions = { middleware: authenticationHandler, }; const client = Client.initWithMiddleware(clientOptions); ``` -------------------------------- ### Migrate to ImplicitMSALAuthenticationProvider (v2.x.x) Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/wiki/Migration-from-1.x.x-to-2.x.x Updated initialization for MSAL authentication provider using ImplicitMSALAuthenticationProvider, msalConfig, and MSALAuthenticationProviderOptions in version 2.x.x. ```typescript const msalConfig = { auth: { clientId: "your_client_id"; // Client Id of the registered application redirectUri: "your_redirect_uri", }, }; const graphScopes = ["user.read", "mail.send"]; // An array of graph scopes const msalInstance = new Msal.UserAgentApplication(msalConfig); const options = new MicrosoftGraph.MSALAuthenticationProviderOptions(graphScopes); const authProvider = new MicrosoftGraph.ImplicitMSALAuthenticationProvider(msalInstance, options); ``` -------------------------------- ### Browser Field for Environment-Specific Implementation Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/design/publishing.md Demonstrates using the 'browser' field to map modules to browser-compatible alternatives. This allows for different implementations based on the runtime environment. ```json "browser": { "stream": "stream-browserify", "Feature-Node.js": "Feature-Browser.js" } ``` -------------------------------- ### Clone Your Forked Repository Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/CONTRIBUTING.md Clone your forked repository to your local machine after setting up Git. ```git git clone https://github.com//.git ``` -------------------------------- ### Import Microsoft Graph Client and Fetch Polyfill in TypeScript Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/README.md Import the Microsoft Graph client and a fetch polyfill into your TypeScript module. Choose a fetch polyfill that suits your project requirements. ```typescript import "isomorphic-fetch"; // or import the fetch polyfill you installed import { Client } from "@microsoft/microsoft-graph-client"; ``` -------------------------------- ### Implement Custom AuthenticationProvider Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/CustomAuthenticationProvider.md Create a custom class that implements the `AuthenticationProvider` interface. This class should contain the logic for obtaining and refreshing access tokens. ```typescript // MyAuthenticationProvider.ts import { AuthenticationProvider } from "@microsoft/microsoft-graph-client"; class MyAuthenticationProvider implements AuthenticationProvider { /** * This method will get called before every request to the msgraph server * This should return a Promise that resolves to an accessToken (in case of success) or rejects with error (in case of failure) * Basically this method will contain the implementation for getting and refreshing accessTokens */ public async getAccessToken(): Promise {} } ``` -------------------------------- ### Initialize AuthCodeMSALBrowserAuthenticationProvider (CDN/Script) Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/AuthCodeMSALBrowserAuthenticationProvider.md Initialize the AuthCodeMSALBrowserAuthenticationProvider when using CDN or script tags. This assumes msal-browser and graph-js-sdk are loaded. ```javascript const msalClient = new msal.PublicClientApplication(msalConfig); const authProvider = new MSGraphAuthCodeMSALBrowserAuthProvider.AuthCodeMSALBrowserAuthenticationProvider(msalClient, { account, scopes: ["user.read", "mail.send"], interactionType: msal.InteractionType.Popup, }); // Initialize the Graph client const graphClient = MicrosoftGraph.Client.initWithMiddleware({ authProvider }); ``` -------------------------------- ### Import MSALAuthenticationProviderOptions from @microsoft/microsoft-graph-client/authProviders/msal Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/wiki/Microsoft-Graph-JavaScript-SDK-V3.0-Upgrade-Guide Shows an alternative import path for MSALAuthenticationProviderOptions when using the Microsoft Graph JS SDK. ```javascript import { MSALAuthenticationProviderOptions } from "@microsoft/microsoft-graph-client/authProviders/msal"; ``` -------------------------------- ### Current LargeFileUploadTask Implementation Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/design/large-file-upload-task-design.md Illustrates the existing structure and upload logic of the LargeFileUploadTask, including interfaces for options and file objects, and the core upload and file slicing methods. ```TypeScript interface LargeFileUploadTaskOptions { rangeSize?: number; } interface FileObject { content: ArrayBuffer | File; name: string; size: number; } // Create a LargeFileUploadTask object with the file object constructor(client: Client, file: FileObject, uploadSession: LargeFileUploadSession, options: LargeFileUploadTaskOptions = {}) ``` ```TypeScript // Call the LargeFileUploadTask.upload() function to upload large file to the API in ranges. upload() { while (true) { const fileSlice = this.sliceFile(nextRange); const response = await this.uploadSlice(fileSlice, nextRange, this.file.size); // Upon completion of upload process incase of onedrive, driveItem is returned, which contains id if (response.id !== undefined) { return response; } else { this.updateTaskStatus(response); } } } ``` ```TypeScript // Function to slice the file as per the "Next Expected Ranges". sliceFile(range: Range): ArrayBuffer | Blob { const blob = this.file.content.slice(range.minValue, range.maxValue + 1); return blob; } ``` -------------------------------- ### Setting AbortController.signal for MSGraph SDK Client Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/CancellingAHTTPRequest.md This snippet shows how to initialize the Microsoft Graph SDK client with an AbortController signal. It includes importing necessary modules, creating an AbortController, setting a timeout to abort the request, and passing the signal within fetch options during client initialization. Use this when you need to implement request cancellation for SDK calls. ```typescript import { Client,FetchOptions } from "@microsoft/microsoft-graph-client"; import { AbortController } from "abort-controller"; // <- import when using the abort-controller npm package. const controller = new AbortController(); const timeout = setTimeout(() => { controller.abort(); }, 150); const fetchOptions: FetchOptions = { signal: controller.signal; } const client = Client.initWithMiddleware({ fetchOptions, // Pass the FetchOptions value where the AbortController.signal is set authProvider, ... }); ``` -------------------------------- ### Initialize Client with Custom Hosts Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/changelogs/v3-upgrade-guide.md Configure the Microsoft Graph client to target custom hosts by providing a Set of hostnames to the `customHosts` option. This ensures that `AuthenticationHandler` and `TelemetryHandler` only add or update request headers for specified Graph or custom endpoints. ```typescript const customHost = "CUSTOM_HOST"; const customHosts = new Set([customHost]); const client = Client.initWithMiddleware({ middleware, customHosts }); ``` -------------------------------- ### Add promise and fetch polyfills for older browsers Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/wiki/Migration-from-1.x.x-to-2.x.x If your application's supported browsers lack native support for Promise and Fetch, include these polyfill script tags in your HTML file. ```html ``` -------------------------------- ### Stage All Changes for Commit Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/CONTRIBUTING.md Stages all modified and new files in the repository for the next commit. This command recursively adds all files in subfolders. ```bash git add . ``` -------------------------------- ### Folder Structure Changes in V3 Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/wiki/Microsoft-Graph-JavaScript-SDK-V3.0-Upgrade-Guide Illustrates the updated folder structure for ES and CJS modules in the Microsoft Graph JS SDK V3. ```text lib │ └─── src (CJS modules) | │ └─── es |___ src (ES modules) ``` -------------------------------- ### MIDDLEWAREOPTIONS Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/OtherAPIs.md Customize per-request middleware behavior using `.middlewareOptions()`. This method accepts an array of strongly typed middleware options, implementing the `IMiddlewareOptions` interface. ```APIDOC ## MIDDLEWAREOPTIONS You can override the client middleware behavior by setting per request middleware options. Use the `.middlewareOptions()` request builder method to add custom middleware behavior for a specific request. The `middlewareOptions()` method takes an array of strongly typed middleware options. These middleware options are an implementation of the [MiddlewareOptions](../src/middleware/options/IMiddlewareOptions.ts) interface. ```typescript try { let res = await client .api("/me/messages") .middlewareOptions([new RetryHandlerOptions(5000)]) .get(); console.log(res); } catch (error) { throw error; } ``` ``` -------------------------------- ### Configure LargeFileUploadTask Options with Progress Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/tasks/LargeFileUploadTask.md Sets up options for the LargeFileUploadTask, including a custom range size and an upload event handler for progress tracking. The 'extraCallBackParam' can be used to pass additional data to the progress handler. ```typescript const progress = (range?: Range, extraCallBackParam?: unknown) => { // Handle progress event }; const uploadEventHandlers: UploadEventHandlers = { progress, extraCallBackParam, }; const options: LargeFileUploadTaskOptions = { rangeSize: 327680, uploadEventHandlers: UploadEventHandlers, }; ``` -------------------------------- ### Checkout New Branch Source: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/CONTRIBUTING.md Switches your working directory to the specified branch, updating files to the branch's current state. This command is used to verify content after creating or switching to a new branch. ```bash git checkout X2 ```