Bliss for the lazy developer : the MS Graph Toolkit

"A good developer is a lazy developer". That's something I've been told in the past. You shouldn't take it too literaly though. It means that you shouldn't write it yourself, when something can be done with standard functionalities, libraries or tools. Microsoft recently dropped the MS Graph toolkit, which makes it easier to create solutions targetting Microsoft Graph. Today I'll have a look at how this can help us in a SharePoint framework solution.

Let's imagine an SPFX solution in which we need to show the Todo items for the logged on person. In Graph I need to address following URL for getting the tasks in the default ToDo list:

https://graph.microsoft.com/v1.0/me/todo/lists/AAMkADI5ZmU4ZmY4LWEzZGQtNDZlMS04YTM2LTI4MTc0NGI5YmIyNwAuAAAAAACcpXDx9lqqRbqZiOBY7OjwAQChhNHLRVScQJBh2LuUX06kAAAAAAESAAA=/tasks

Of course your solution need the necessary permissions, so you need to ask for this in the package-solution.json.

    "webApiPermissionRequests": [
      {
        "resource": "Microsoft Graph",
        "scope": "Tasks.ReadWrite"
      }

And with a bit of code we can create a serviceclient class for getting the information.

export class TodoService  {
    constructor(public ctx:WebPartContext) {}

    private async getGraphClient():Promise<MSGraphClientV3>{ 
        const gClient = await this.ctx.msGraphClientFactory.getClient("3"); 
        return gClient; 
    }
    
    async getTodos():Promise<MSGraph.TodoTask[]> {
        let gClient = await this.getGraphClient();
        let todos:any = await gClient
                        .api('/me/todo/lists/AAMkADI5ZmU4ZmY4LWEzZGQtNDZlMS04YTM2LTI4MTc0NGI5YmIyNwAuAAAAAACcpXDx9lqqRbqZiOBY7OjwAQChhNHLRVScQJBh2LuUX06kAAAAAAESAAA=/tasks')
                        .get();

        return todos.value;
    }
}

And with some minimal effort we can show this.

export default class ToDos extends React.Component<{}, IToDosState> {

  constructor() {
    this.state = {data:[]};
  }

  componentDidMount(): void {
    this.props.service.getTodos().then(r=> {
      this.setState({data:r});
    }).catch(err=>console.log(err));
  }

  public render(): React.ReactElement<IToDosProps> {
    const data = this.state.data.map(el=><li key={el.id}>{el.title}</li>);
    return (
      <>
        <div>Todos</div>
        <ul>{data}</ul>
      </>
    );
  }
}

Okay, the UI is really minimalistic, I know. And the code is not too complex, but still, it can get easier !!! Let's use the MS Graph Toolkit. First add it to your project with

npm i @microsoft/mgt-spfx

Let's create a new webpart now. There's a few things that we must do. First we need to initialize some providers. In the Graph toolkit, Providers will take care of authentication.

import { Providers, SharePointProvider } from '@microsoft/mgt-spfx';

export default class ToDo2WebPart extends BaseClientSideWebPart<IToDo2WebPartProps> {
    //...
    protected onInit(): Promise<void> {
    if (!Providers.globalProvider) {
      Providers.globalProvider = new SharePointProvider(this.context);
    }
    return Promise.resolve();
  }
}

And then we can show the todo's like this:

  public render(): void {
    this.domElement.innerHTML = `<div>
      <mgt-todo></mgt-todo>
    </div>
    `
  }

And that's it. How easy is that. It even looks good. Like I said, bliss for the lazy developer.