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

2 comments:

  1. Hi Mikael, This is great, thanks.
    Although I get a strange error on this line...
    this._graphClient = await context.msGraphClientFactory.getClient();
    Type 'MSGraphClient' is not assignable to type 'MSGraphClient'. Two different types with this name exist, but they are unrelated.

    I've checked for multiple imports, reloaded node modules, etc but nothing seems to work.
    I've recently updated this to SPFX 1.6, successfully other than this, but that might be the cause

    ReplyDelete
    Replies
    1. Try "npm dedupe" then build. When updating use the Office 365 CLI, as it gives all steps needed for a proper upgrade. You may also nuke node_modules and reinstall before building.

      Delete