(7/7) Insert Code Snippet & Execute
Step 8: Define Parameters for the Code to Execute
Language: Node.js 16 x
Secrets: HubSpot Access Key from Private App
Secret Constant defined as "secretName"
Property to include in code: Define the constant as “phone,” which is equal to the “phone number” property in the contact object
HubSpot Client: v3
Step 9: Copy & Paste This Code Snippet, Then Test the Workflow
Code Snippet:
const DEDUPE_PROPERTY = 'phone';
const hubspot = require('@hubspot/api-client');
exports.main = async (event, callback) => {
try {
const hubspotClient = new hubspot.Client({
accessToken: process.env.secretName
});
const contactResult = await hubspotClient.crm.contacts.basicApi.getById(event.object.objectId, [DEDUPE_PROPERTY]);
let dedupePropValue =
contactResult.body.propertie…[DEDUPE_PROPERTY];
console.log(`Looking for duplicates based on ${DEDUPE_PROPERTY} = ${dedupePropValue}`);
const searchResults = await hubspotClient.crm.contacts.searchApi.doSearch({
filterGroups: [{
filters: [{
propertyName: DEDUPE_PROPERTY,
operator: 'EQ',
value: dedupePropValue
}]
}]
});
let idsToMerge = searchResults.body.results
.map(contact =>
contact.id)
.filter(vid => Number(vid) !== Number(event.object.objectId));
if (idsToMerge.length > 0) {
console.log(`Found multiple potential contact IDs to merge: ${idsToMerge.join(', ')}`);
// Merge all contacts into the first one found
for (let i = 1; i < idsToMerge.length; i ) {
await hubspotClient.apiRequest({
method: 'POST',
path: `/contacts/v1/contact/merge-vids/${idsToMerge[0]}`,
body: {
vidToMerge: idsToMerge[i]
}
});
console.log(`Merged contact id=${idsToMerge[i]} into contact id=${idsToMerge[0]}`);
}
} else {
console.log('No matching contact, nothing to merge');
}
} catch (error) {
console.error('An error occurred:', error);
}
};