Microsoft Graph JavaScript SDK에는 코드를 간소화하고 앱 빌드에 집중할 수 있는 기능이 포함되어 있습니다.
SDK를 사용하면 다음을 더 쉽게 수행할 수 있습니다.
- 서비스가 부하가 많이 발생하는 경우와 같이 예상대로 작동하지 않는 경우에 대한 API 오류 처리
- 일괄 처리 요청과 같은 복잡한 API 작업 수행
- 사용자의 사진 가져오기와 같은 이진 응답 처리
페치에서 Graph JavaScript SDK로 마이그레이션
Fetch 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 제한 오류를 감시하고 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