Thursday, September 27, 2018

Example of wrapper to ease usage of Graph calls in SPFx

silhouette of trees and purple lightning

Waldek Mastykarz wrote a good post about not passing the web part context all around your React components, which is good advice. And as Waldek pointed out after reviewing my code I pass the full context and not just the GraphClient. So ideally, passing just what you need is better, but I’m lazy at times :) And it gives you the reader an opportunity to improve my code :)

I tend to create static helper classes, and here’s one approach to ease calling Graph API’s throughout your solution.

The wrapper class is quite simple, and I’ve created helper methods for GET, POST, PATCH, DELETE.

To use this you would first initialize the class in your main web part code.

public async render(): Promise<void> {
   await MSGraph.Init(this.context);
   ...
}

and somewhere in your code if you wanted to get Group data for a group you could use something like this:

import { MSGraph } from '../services/MSGraph';

...

let groupId = this.props.context.pageContext.legacyPageContext.groupId;
let graphUrl = `/groups/${groupId}`;
let group = await MSGraph.Get(graphUrl);

Photo by Jeremy Thomas at Unsplash