Wednesday, September 13, 2017

SharePoint Framework helper class for calling the Microsoft Graph

I’m creating a couple of web parts using SharePoint Framework in my current project so I figured I’d share a small helper class I created for performing GET requests against the Microsoft Graph. The code is written in TypeScript and handles single item results as well as paging on array results.

MSGraph.ts

import { GraphHttpClient, GraphHttpClientResponse } from '@microsoft/sp-http';

export class MSGraph {
    public static async Get(graphClient: GraphHttpClient, url: string) {
        let values: any[] = [];
        while (true) {
            let response: GraphHttpClientResponse = await graphClient.get(url, GraphHttpClient.configurations.v1);
            // Check that the request was successful
            if (response.ok) {
                let result = await response.json();
                let nextLink = result["@odata.nextLink"];
                // Check if result is single entity or an array of results
                if (result.value && result.value.length > 0) {
                    values.push.apply(values, result.value);
                }
                result.value = values;
                if (nextLink) {
                    url = result["@odata.nextLink"].replace("https://graph.microsoft.com/", "");
                } else {
                    return result;
                }
            }
            else {
                // Reject with the error message
                throw new Error(response.statusText);
            }
        }
    }
}

You can use the code as follows where I have extended the properties to include the web part context object in order to pass in graphHttpClient object.

import { MSGraph } from './MSGraph';

...

try {
  let groups = await MSGraph.Get(this.props.context.graphHttpClient, "v1.0/groups?$top=5");
} catch (error) {
  console.error(error);
}