Since from April the Contacts API will be deprecated I'm making the switch to the People API.
I'm using the code suggested by Google to find a contact starting from email. This is the function:
function getContactByEmail(email) {
var email = "anExistingMailInMyContacts@gmail.com";
try {
// Gets the person with that email address by iterating over all contacts.
const people = People.People.Connections.list('people/me', {
personFields: 'names,emailAddresses'
});
const contact = people['connections'].find((connection) => {
const emailAddresses = connection['emailAddresses'];
return emailAddresses && emailAddresses.length > 0 && emailAddresses.some((emailAddress) => emailAddress['value'] === email);
});
// Prints the contact.
console.log('People: %s', JSON.stringify(people, null, 2));
console.log('Contact: %s', JSON.stringify(contact, null, 2));
} catch (err) {
// TODO (developers) - Handle exception
console.log('Failed to get the connection with an error %s', err.message);
}
}
The problem is that the People API only fetch a very small subset of my contacts. Thanks to the line console.log('People: %s', JSON.stringify(people, null, 2)); I discovered that there are only very few contacts extracted. And they are always the same.
Ho can I fetch all my contacts?
What Cooper says is true. It is possible that your response is not complete because you are just counting on the result from the first page.
Perhaps you need to utilize the nextPageToken and perform paging.
You can obtain all pages of the response by using this code as sample:
function myFunction() {
console.log("Printing contacts: ")
let allConnections = listAllContacts();
allConnections.forEach(function(connection) { console.log(connection.names[0].displayName) })
}
function listAllContacts(){
let allContacts = []
var nextPageToken;
let pageNumber = 0
do {
console.log("Getting page " + ++pageNumber + " with nextPageToken: " + nextPageToken)
var response = getContacts(nextPageToken);
allContacts = allContacts.concat(response.connections)
} while (nextPageToken = response.nextPageToken)
return allContacts;
}
function getContacts(nextPageToken = null) {
return PeopleAPI.People.Connections.list("people/me", {
personFields: "names",
pageToken: nextPageToken,
pageSize: 5
});
}
This is the result of the console:
The people.connections.list method will only return the contacts under your https://contacts.google.com/ contacts page. To get the contacts under Other contacts use the otherContacts.list method instead.