更新应用程序代码以使用 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,并在再次调用 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