Microsoft Graph JavaScript SDK 隨附可簡化程式代碼的功能,並讓您專注於建置應用程式。
使用 SDK 可讓您更輕鬆地:
- 處理未如預期運作的 API 錯誤,例如服務在負載過重的情況下節流
- 執行複雜的 API 作業,例如批次要求
- 處理二進位回應,例如取得使用者相片
從 fetch 遷移至 Graph JavaScript SDK
如果您使用擷取 API 在 JavaScript 應用程式中呼叫 API,您可能會有類似下列的程式代碼:
const msalClient = new msal.PublicClientApplication({
auth: {
clientId: appId
}
});
function getAccessToken(msalClient) {
const accounts = msalClient.getAllAccounts();
if (accounts.length > 0) {
const accessTokenRequest = {
scopes: [
'https://graph.microsoft.com/User.Read'
],
account: accounts[0]
};
return msalClient.acquireTokenSilent(accessTokenRequest)
.then(response => response.accessToken)
.catch(error => {
console.log(error);
console.log("silent token acquisition fails. acquiring token using redirect");
if (error instanceof msal.InteractionRequiredAuthError) {
return msalClient.acquireTokenRedirect(accessTokenRequest);
}
});
}
else {
return Promise.reject('Sign in');
}
}
msalClient
.loginPopup()
.then(response => getAccessToken(msalClient))
.then(accessToken => fetch('https://graph.microsoft.com/v1.0/me', {
method: 'GET',
headers: {
authorization: `Bearer ${accessToken}`
}
}))
.then(response => response.json())
.then(json => {
// do something here
});
若要使用 Graph JavaScript SDK,您會將程式代碼變更為:
const msalClient = new msal.PublicClientApplication({
auth: {
clientId: appId
}
});
function getGraphClient(account) {
const authProvider = new MSGraphAuthCodeMSALBrowserAuthProvider.AuthCodeMSALBrowserAuthenticationProvider(msalClient, {
account,
scopes: [
'https://graph.microsoft.com/User.Read'
],
interactionType: msal.InteractionType.Popup,
});
return MicrosoftGraph.Client.initWithMiddleware({ authProvider });
}
msalClient
.loginPopup()
.then(response => {
const accounts = msalClient.getAllAccounts();
if (accounts.length > 0) {
const graphClient = getGraphClient(accounts[0]);
return graphClient.api('/me').get();
}
else {
return Promise.reject('Sign in');
}
})
.then(json => {
// do something here
});
處理 API 錯誤
在大規模使用時,使用 Microsoft Graph 體驗的應用程式最常見的 API 錯誤之一是節流。 當伺服器負載過重時,就會發生此情況。 節流會降低伺服器上的負載,讓服務保持運作。
由於限制很少發生在開發人員租戶上,因此開發人員通常呼叫 API,而不會妥善處理錯誤:
fetch('https://graph.microsoft.com/v1.0/me', {
method: 'GET',
headers: {
authorization: `Bearer ${accessToken}`
}
})
.then(response => response.json())
.then(json => {
// do something here
});
處理擷取 API 節流錯誤的正確方式,是擴充呼叫,以留意 429 節流錯誤,並等候 API 再次呼叫 API,以取得 retry-after 回應標頭中指定的秒數。 更新的程式代碼如下所示:
function sleep(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
async function fetchAndRetryIfNecessary(callAPIFn) {
const response = await callAPIFn();
if (response.status === 429) {
const retryAfter = response.headers.get('retry-after');
await sleep(retryAfter * 1000);
return fetchAndRetryIfNecessary(callAPIFn);
}
return response;
}
const response = await fetchAndRetryIfNecessary(async () => (
await fetch('https://graph.microsoft.com/v1.0/me', {
method: 'GET',
headers: {
authorization: `Bearer ${accessToken}`
}
})
));
const json = await response.json();
// do something here
處理節流和其他錯誤的更簡單方法是使用 Graph JavaScript SDK,因為它能自動為您處理這些錯誤。
const json = await graphClient.api('/me').get();
// do something here