更新应用程序代码以使用 Microsoft Graph JavaScript SDK

概览
目标: 迁移到 Graph JS SDK
时间: 30 分钟
插件: 没有
先决条件:设置开发代理

Microsoft Graph JavaScript SDK 附带了简化代码的功能,让你专注于生成应用。

使用 SDK 可以更轻松地:

  • 处理在事物无法按预期工作时的 API 错误,例如服务在负载过大时受到限制的情况
  • 执行复杂的 API 操作,例如批量请求
  • 处理二进制响应,例如获取用户的照片

从 Fetch API 迁移到 Graph JavaScript SDK

如果您在 JavaScript 应用中使用 fetch API 调用 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 之前等待响应标头中指定的 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

另请参阅