mods-client v0.1.2
mods-cleint: MODS Client SDK library for JavaScript and TypeScript
The mods-client library is part of the Microsoft Office Developer Services SDK. It facilitates development of client-side components in Teams applications. Use this SDK when you are developing a front end web page for a Teams app and needs to access the Microsoft Graph or make a call to an Azure Function on-behalf-of the user.
Usage
run npm install mods
at your project and use import
syntax to import modules. For example:
import * as MODS from "mods-client"
More Information
Find more information in the Microsoft documentation:
Accessing Microsoft Graph as the connected user
Access the Microsoft Graph is a common task. You will use it for sending email, accessing SharePoint lists, and more. The MODS client library makes it easy to get an authenticated Microsoft Graph client.
The most common situation will be that you want to access data within the Microsoft Graph on behalf of the connected user. Use the following code:
await MODS.init();
try {
const scopes = [ 'user.read' ]
const graphClient = await MODS.getMicrosoftGraphClient(scopes);
// Use the graphClient here; for example - this obtains the users profile
const result = await graphClient.api('/me').get();
} catch (err) {
// Handle errors here
return { res: { status: 400, body: JSON.stringify(err) }};
}
Getting information on the connected user
When user logs in Teams Client, some basic information can be obtained to identify the user. You can use getUserInfo()
to achieve this:
await MODS.init();
const { displayName, objectId, preferredUserName } = MODS.getUserInfo();
The objectId
is the object ID of the user within AAD and is guaranteed not to change even if the username or display name is changed. This allows it to be used as a primary key in database operations.
Obtaining an access token by asking user to login
In an exaple of calling Graph API, we would first try to get access token from memory and localStorage. If no token exists, we would acquire the token from MODS. If MODS also doesn't have the token, it would throw an error. In this case, MODS client library provides a function for a function for you to ask user to login and then obtain an access token.
await MODS.init();
try {
// Calling Graph API to get user profile photo that throws an error.
const graphClient = MODS.getMicrosoftGraphClient();
const profile = await graphClient.api("/me").get();
const photoBlob = await graphClient.api("/me/photos('120x120')/$value").get();
} catch (err) {
if (err.message.indexOf("Access token is expired or invalid") >= 0) {
// Popup login page to get Microsoft Graph access token
// The access token would be managed by the SDK and cached in localStorage
MODS.popupLogInPage();
//... use graph client
}
}
Error Handling
Each method in the MODS service client will throw a MODSError
when it encounters an error. The MODSError
object contains message
property. Use message
to display human readable description of the error.