是否可以使用Google People API批量删除联系人?

时间:2018-12-07 08:41:12

标签: google-people

我发现Contact API中有批处理操作。但这是XML格式,我更喜欢在People API中使用JSON格式。有可能吗?

2 个答案:

答案 0 :(得分:0)

这可以通过使用contactGroup来完成:

  • 使用contactGroup.create创建一个临时组。
  • 添加所有要删除的成员 contactGroup.members.modify。
  • 使用contactGroup.delete删除临时组,然后 使用deleteContacts = true。

答案 1 :(得分:0)

您需要使用 Google batch API。

const { google }  = require('googleapis')


function extractJSON (str) {
  const result = []

  let firstOpen  = 0
  let firstClose = 0
  let candidate  = 0

  firstOpen = str.indexOf('{', firstOpen + 1)

  do {
    firstClose = str.lastIndexOf('}')

    if ( firstClose <= firstOpen ) {
      return []
    }

    do {
      candidate = str.substring(firstOpen, firstClose + 1)

      try {
        result.push(JSON.parse(candidate))
        firstOpen = firstClose
      } catch (e) {
        firstClose = str.substr(0, firstClose).lastIndexOf('}')
      }

    } while ( firstClose > firstOpen )

    firstOpen = str.indexOf('{', firstOpen + 1)

  } while ( firstOpen !== -1 )

  return result
}

async function batchDeleteContacts (resourceIds) {

  /*
    resourceIds = [
      'c1504716451892127784',
      'c1504716451892127785',
      'c1504716451892127786,
      ....'
    ]


    Setup your google-api client and extract the oauth header/
  */
  const authHeader = await google.oAuth2Client.getRequestHeaders()

  let counter   = 0
  let confirmed = []

  try {
    do {
      const temp = resourceIds.splice(0, 25)

      const multipart = temp.map((resourceId, index) => ({
        'Content-Type': 'application/http',
        'Content-ID': (counter * 25) + index,
        'body': `DELETE /v1/people/${resourceId}:deleteContact HTTP/1.1\n`
      }))

      const responseString = await request.post({
        url: 'https://people.googleapis.com/batch',
        method: 'POST',
        multipart: multipart,
        headers: {
          'Authorization': authHeader.Authorization,
          'content-type': 'multipart/mixed'
        }
      })

      const result = extractJSON(responseString)
      confirmed = confirmed.concat(result)

      counter ++

    } while ( resourceIds.length > 0 )

  } catch (ex) {

    // Handling exception here
  }

  return confirmed
}