Created
March 29, 2022 19:10
-
-
Save aflyen/647c2af1bb037d4a4d92839bd9d2db6f to your computer and use it in GitHub Desktop.
Baseline service for SharePoint Framework projects based on the service locator pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ServiceKey, ServiceScope } from '@microsoft/sp-core-library'; | |
import { SPHttpClient, MSGraphClientFactory, MSGraphClient } from '@microsoft/sp-http'; | |
import { PageContext } from '@microsoft/sp-page-context'; | |
export interface ICustomService { | |
getMyProfile(): Promise<IGraphUser>; | |
} | |
export interface IGraphUser { | |
businessPhones?: string[]; | |
displayName?: string; | |
givenName?: string; | |
jobTitle?: any; | |
mail?: string; | |
mobilePhone?: any; | |
officeLocation?: any; | |
preferredLanguage?: string; | |
surname?: string; | |
userPrincipalName?: string; | |
id?: string; | |
} | |
export class CustomService implements ICustomService { | |
public static readonly serviceKey: ServiceKey<ICustomService> = | |
ServiceKey.create<ICustomService>('corp:CustomService', CustomService); | |
private _msGraphClientFactory : MSGraphClientFactory; | |
private _spHttpClient: SPHttpClient; | |
private _pageContext: PageContext; | |
private _currentWebUrl: string; | |
constructor(serviceScope: ServiceScope) { | |
serviceScope.whenFinished(() => { | |
this._msGraphClientFactory = serviceScope.consume(MSGraphClientFactory.serviceKey); | |
this._spHttpClient = serviceScope.consume(SPHttpClient.serviceKey); | |
this._pageContext = serviceScope.consume(PageContext.serviceKey); | |
this._currentWebUrl = this._pageContext.web.absoluteUrl; | |
}); | |
} | |
/** | |
* Get current users profile | |
* @returns | |
*/ | |
public async getMyProfile(): Promise<IGraphUser> { | |
let user: IGraphUser = null; | |
try { | |
let client = await this._msGraphClientFactory.getClient(); | |
user = await client.api('/me').get(); | |
} catch (error) { | |
console.debug("Error getting user profile with Graph: " + error); | |
} | |
return user; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment