Microsoft Graph JavaScript SDK를 사용하도록 애플리케이션 코드 업데이트
Microsoft Graph JavaScript SDK에는 코드를 간소화하고 앱 빌드에 집중할 수 있는 기능이 함께 제공됩니다.
SDK를 사용하면 다음을 더 쉽게 수행할 수 있습니다.
- 서비스가 부하가 많은 상태에서 제한되는 경우와 같이 예상대로 작동하지 않는 경우에 대한 API 오류 처리
- 일괄 처리 요청과 같은 복잡한 API 작업 수행
- 사용자의 사진 가져오기와 같은 이진 응답 처리
페치에서 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 제한 오류에 대해 watch 호출을 확장하고 응답 헤더에 retry-after
지정된 시간(초)에 대해 API를 다시 호출하기 전에 기다리는 것입니다. 업데이트된 코드는 다음과 같습니다.
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
GitHub에서 Microsoft와 공동 작업
이 콘텐츠의 원본은 GitHub에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
Dev Proxy