首页 > 解决方案 > 如何使用 People API 从 Google 联系人中获取所有(超过 2000 个)联系人

问题描述

我正在使用 Node.js 开发 Google API。我需要从谷歌联系人中检索所有联系人列表。列表中有超过 2000 个联系人,但页面大小限制为 2000,所以我只得到 2000 个联系人,使用“people.connections.list”方法。有人可以帮忙吗?如何获取所有联系人?

标签: node.jsoauth-2.0google-api

解决方案


我设法通过使用递归和一些 ES6 特性让它工作。

诀窍是nextPageToken在下一个请求中使用上一个请求的返回值,因为根据文档, people.connections.list的最大限制为 2000。

const getAllContacts = async (googleApi, current = [], pageToken = undefined) => {
  const { 
    data: { connections, nextPageToken, totalItems } 
  } = await googleApi.connections.list({
    resourceName: 'people/me',
    pageSize: 2000,
    personFields: 'emailAddresses,phoneNumbers', // or whatever personFields you want
    ...(pageToken ? { pageToken } : {})
  });

  // merge contacts from this request with data from your previous requests
  const contacts = [...current, ...connections];

  if (nextPageToken && contacts.length < totalItems) {
    return getAllContacts(googleApi, contacts, nextPageToken);
  }

  return contacts;
}

要使用此方法,请确保它googleAPI是 people api 的实例,如下所示

const { people } = google.people({ version: 'v1' });
const contacts = await getAllContacts(people);

推荐阅读