Need help, code doesn't work

Kineticmedic
Member

I'm trying to modify the template provided for deduplicating contact records to allow it to deduplicate company records, but as the code appears to have been built against the V1 API, not the V3 which is what documentation references, plus my general unfamiliarity with node.js (I'm a C++ boy) I'm stumped what's going wrong and support doesn't want to help.

 

Here's my code as follows:

 

/**
 * 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.spoonybard;

// 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 = 'company name';

exports.main = (event, callback) => {
  const hubspotClient = new hubspot.Client({ accessToken: HUBSPOT_PRIVATE_APP_ACCESS_TOKEN });

  hubspotClient.crm.companies.basicApi
    .getById(event.object.objectId, [PROPERTY_USED_TO_DEDUPE_CONTACTS])
    .then(companyResult => {
      let dedupePropValue = companyResult.body.properties[PROPERTY_USED_TO_DEDUPE_CONTACTS];

      console.log(`Looking for duplicates based on ${PROPERTY_USED_TO_DEDUPE_CONTACTS} = ${dedupePropValue}`);
      hubspotClient.crm.companies.searchApi.doSearch({
          filterGroups: [{
            filters: [{
              propertyName: PROPERTY_USED_TO_DEDUPE_CONTACTS,
              operator: 'EQ',
              value: dedupePropValue
            }]
          }]
        })
        .then(searchResults => {
          let idsToMerge = searchResults.body.results
            .map(object => object.id)
            .filter(vid => Number(vid) !== Number(event.object.objectId));

          if (idsToMerge.length == 0) {
            console.log('No matching company, nothing to merge');
            return;
          } else if (idsToMerge.length > 1) {
            console.log(`Found multiple potential company IDs ${idsToMerge.join(', ')} to merge`);
            throw new Error("Ambiguous merge; more than one matching company");
          }

          let idToMerge = idsToMerge[0];
          console.log(`Merging enrolled company id=${event.object.objectId} into company id=${idToMerge}`);
          hubspotClient
            .apiRequest({
              method: 'POST',
              path: `/crm/v3/objects/companies/merge/${idToMerge}`,
              body: {
                vidToMerge: event.object.objectId
              }
            })
            .then(mergeResult => {
              console.log('Companies merged!');
            });
        });
    });
};

 

Any and all help appriciated as we have only a few days left to resolve this and fix what was a bad data merge caused by a 3rd party and I'm not really even a developer, rather the only resource with spare time to try.

0 Upvotes
3 Replies 3
andreaska
Participant

 Hi @Kineticmedic 

 

Three things:

1. When using promises, ensure you provide the `catch`-blocks.

2. In your final promise resolving function call the `callback` function.

3. Do not access the `body` property of the result.

 

Review the example code below to get another starting point.

 

const hubspot = require('@hubspot/api-client');

exports.main = (event, callback) => {
const PROPERTY_USED_TO_DEDUPE_CONTACTS = 'name';
const hubspotClient = new hubspot.Client({accessToken: process.env.HUBSPOT_API_ACCESS_TOKEN});

hubspotClient.crm.companies.basicApi.getById(4370248339, ['name']).then(companyResult => {
const dedupePropValue = companyResult.properties[PROPERTY_USED_TO_DEDUPE_CONTACTS];
console.log(`Looking for duplicates based on ${PROPERTY_USED_TO_DEDUPE_CONTACTS} = ${dedupePropValue}`);
hubspotClient.crm.companies.searchApi.doSearch({
filterGroups: [{
filters: [{
propertyName: PROPERTY_USED_TO_DEDUPE_CONTACTS,
operator: 'EQ',
value: dedupePropValue
}]
}]
})
.then(searchResults => {
// add further code here


// final call here
callback({})
}).catch(ex => {
console.error(ex)
});
}).catch(ex => {
console.error(ex)
});
};

 

 

 

0 Upvotes
Jaycee_Lewis
Thought Leader

Hi, @Kineticmedic 👋 Thanks for stepping up and trying to tackle this challenge. I'd like to invite some of our community members to the conversation — hey @himanshurauthan @ChrisoKlepke @taran42 @andreaska, do you have any troubleshooting tips for @Kineticmedic?

 

Two things I have to offer off of the top of my head are:

  • Make sure you are using the internal value and not the label for the Contact property you are using. For example, in Contacts > Properties > Company Name, we can see the internal value for this property is company, not company name or company_name
    CleanShot 2023-06-16 at 17.45.30.png

  • For the merge request body, can you try the following format?
    hubspotClient.apiRequest({
        method: 'POST',
        path: `/crm/v3/objects/companies/${event.object.objectId}/merge-vids`,
        body: {
          primaryObjectId: idToMerge,
          objectIdToMerge: event.object.objectId
        }
    })
    
  • I'm not seeing any catch blocks to handle any failures from the API calls. Consider adding a .catch(error => { console.log(error) }) after every API call to catch and log the errors for debugging

Thank you for the extra details! — Jaycee





loop


Loop Marketing is a new four-stage approach that combines AI efficiency and human authenticity to drive growth.

Learn More




0 Upvotes
Kineticmedic
Member

When testing even after making the changes you suggested I'm still getting the same to me, meaningless error message:

 

Kineticmedic_0-1687009333733.png

 

0 Upvotes