共用方式為


更新應用程式程式代碼以使用 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 處理節流錯誤的適當方式,是將呼叫擴充至 watch 429 節流錯誤,並等候 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