Skip to content

Instantly share code, notes, and snippets.

@anoopt
Last active March 7, 2023 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anoopt/af03de17bcd6230f3bfcc66ff5a05305 to your computer and use it in GitHub Desktop.
Save anoopt/af03de17bcd6230f3bfcc66ff5a05305 to your computer and use it in GitHub Desktop.
Helper wrapper for calling Graph
//* Helper wrapper for calling Graph
//* based on https://gist.github.com/wobba/37416d3107b85675d896105554b3df28
//* Thank you Mikael Svenson
import { WebPartContext } from '@microsoft/sp-webpart-base';
import { GraphError } from '@microsoft/microsoft-graph-client';
import { MSGraphClientV3 } from '@microsoft/sp-http';
export class msgraph {
private static _graphClient: MSGraphClientV3;
public static async Init(context: WebPartContext) {
this._graphClient = await context.msGraphClientFactory.getClient('3');
}
public static async Call(
method: "get" | "post" | "patch" | "delete",
apiUrl: string,
version: "v1.0" | "beta",
content?: any,
selectProperties?: string[],
expandProperties?: string[],
filter?: string,
count?: boolean
): Promise<any> {
var p = new Promise<string>(async (resolve, reject) => {
let query = this._graphClient.api(apiUrl).version(version);
typeof(content) === "object" && (content = JSON.stringify(content));
selectProperties && selectProperties.length > 0 && (query = query.select(selectProperties));
filter && filter.length > 0 && (query = query.filter(filter));
expandProperties && expandProperties.length > 0 && (query = query.expand(expandProperties));
count && (query = query.count(count));
let callback = (error: GraphError, response: any, rawResponse?: any) => error ? reject(error) : resolve(response);
//* ES2016
["post", "patch"].includes(method) ? await query[method](content, callback) : await query[method](callback);
});
return p;
}
}
/* Example to create an item in a SharePoint list */
/*
// do this in the onInit method
await msgraph.Init(this.context);
// do this where needed
const item = await msgraph.Call(
'post',
"/sites/yourtenantname.sharepoint.com,b9d5fdc2...2bfdb1e6a59e,8e5b0360...687268f18466/lists/515c5b63...ce64567e3676/items",
"v1.0",
{
"fields": {
"Title": "Test"
}
}
);
console.log(item);
*/
//* A React custom hook version of msgraph.ts
import * as React from 'react';
import { MSGraphClientV3, MSGraphClientFactory } from '@microsoft/sp-http';
export const useMicrosoftGraph = (msGraphClientFactory: MSGraphClientFactory) => {
const clientRef = React.useRef<MSGraphClientV3>();
const getClient = React.useCallback(async (): Promise<any> => {
if (!msGraphClientFactory) {
return undefined;
}
const client = await msGraphClientFactory.getClient('3');
clientRef.current = client;
}, [msGraphClientFactory]);
const callMicrosoftGraphAPI = React.useCallback(
async (
method: "get" | "post" | "patch" | "delete",
apiUrl: string,
version: "v1.0" | "beta",
content?: any,
selectProperties?: string[],
expandProperties?: string[],
filter?: string,
count?: boolean
): Promise<any> => {
if (!clientRef.current) {
await getClient();
}
const query = clientRef.current.api(apiUrl).version(version);
typeof content === 'object' && (content = JSON.stringify(content));
selectProperties && selectProperties.length > 0 && (query.select(selectProperties));
filter && filter.length > 0 && (query.filter(filter));
expandProperties && expandProperties.length > 0 && (query.expand(expandProperties));
count && (query.count(count));
try {
return await new Promise((resolve, reject) => {
let callback = (error: any, response: any, rawResponse?: any) => {
if (error) {
reject(error);
} else {
resolve(response);
}
};
if (method === 'post' || method === 'patch') {
query[method](content, callback);
} else {
query[method](callback);
}
});
} catch (error) {
console.error(`Error calling Microsoft Graph API: ${error.message}`);
throw error;
}
},
[getClient]
);
return { callMicrosoftGraphAPI };
};
/*
Example usage in a component
import { useMicrosoftGraph } from './hooks';
const { callMicrosoftGraphAPI } = useMicrosoftGraph(props.msGraphClientFactory);
// get the page content from the Microsoft Graph API
const getPageContentUsingGraphAPI = async (): Promise<string> => {
const response = await callMicrosoftGraphAPI(
"get",
`/sites/${siteId}/pages/${pageId}`,
"beta",
null,
["id", "title"],
["webparts($filter=(isof('microsoft.graph.textWebPart')))"],
null
);
return response?.webParts?.map((webPart: any) => webPart.innerHtml)?.join(' ') || '';
};
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment