Skip to content

Instantly share code, notes, and snippets.

@AtlasCan
Created February 25, 2024 08:56
Show Gist options
  • Save AtlasCan/7541d5a8f1a266e4f206ac3f8372a442 to your computer and use it in GitHub Desktop.
Save AtlasCan/7541d5a8f1a266e4f206ac3f8372a442 to your computer and use it in GitHub Desktop.
Hubspot Deduplication Code
/**
* This custom code action removes duplicate contacts based on a specific contact property
*/
// Import required libraries
const hubspot = require('@hubspot/api-client');
/**
* How to access HubSpot's client to make API
* 1) Create a Private App: https://developers.hubspot.com/docs/api/private-apps
* 2) Create a Secret using your Private App's access token via the "Secrets" dropdown above
* 3) Insert your secret below, replacing "YOUR_PRIVATE_APP_ACCESS_TOKEN" with the name of your Secret
*/
const HUBSPOT_PRIVATE_APP_ACCESS_TOKEN = process.env.dwKey;
// By default, phone numbers are used to dedupe contacts (i.e. 2 contacts with the same phone number are merged together)
// Change this property if you would like to use a different property to dedupe contacts with
const PROPERTY_USED_TO_DEDUPE_CONTACTS = 'phone';
exports.main = (event, callback) => {
const hubspotClient = new hubspot.Client({ accessToken: HUBSPOT_PRIVATE_APP_ACCESS_TOKEN });
hubspotClient.crm.contacts.basicApi
.getById(event.object.objectId, [PROPERTY_USED_TO_DEDUPE_CONTACTS])
.then(contactResult => {
let dedupePropValue = contactResult.properties[PROPERTY_USED_TO_DEDUPE_CONTACTS];
console.log(`Looking for duplicates based on ${PROPERTY_USED_TO_DEDUPE_CONTACTS} = ${dedupePropValue}`);
hubspotClient.crm.contacts.searchApi.doSearch({
filterGroups: [{
filters: [{
propertyName: PROPERTY_USED_TO_DEDUPE_CONTACTS,
operator: 'EQ',
value: dedupePropValue
}]
}]
})
.then(searchResults => {
let idsToMerge = searchResults.results
.map(object => object.id)
.filter(vid => Number(vid) !== Number(event.object.objectId));
if (idsToMerge.length == 0) {
console.log('No matching contact, nothing to merge');
return;
} else if (idsToMerge.length > 1) {
console.log(`Found multiple potential contact IDs ${idsToMerge.join(', ')} to merge`);
throw new Error("Ambiguous merge; more than one matching contact");
}
let idToMerge = idsToMerge[0];
console.log(`Merging enrolled contact id=${event.object.objectId} into contact id=${idToMerge}`);
hubspotClient
.apiRequest({
method: 'POST',
path: `/contacts/v1/contact/merge-vids/${idToMerge}`,
body: {
vidToMerge: event.object.objectId
}
})
.then(mergeResult => {
console.log('Contacts merged!');
});
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment