⚙ Operations Hub

sMoyse
Contributor

Custom Code Action Issue - contact property returning undefined

SOLVE

Hi There,

 

I wasn't sure if I should put this in the API or Ops Hub location... I chose the latter. 

 

I'm trying to dedupe contacts based on firstname, lastname and company. Mainly to take care of duplicate contacts as a result of merging two Companies.

 

I've started with the dedupe based on phone number sample and changed it to suit my needs. But the property values keep returning as undefined and I can't figure out why. 

 

I'm just wondering if someone on here can tell what's wrong?

SMoyse_0-1713587076986.png

 

 

 

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

  const DEDUPE_PROPERTY1 = 'firstname';
  const DEDUPE_PROPERTY2 = 'lastname';
  const DEDUPE_PROPERTY3 = 'company';

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

  hubspotClient.crm.contacts.basicApi
    .getById(event.object.objectId, ['email'])
    .then(contactResult => {
      let dedupePropValue1 = contactResult.properties[DEDUPE_PROPERTY1];
      let dedupePropValue2 = contactResult.properties[DEDUPE_PROPERTY2];
      let dedupePropValue3 = contactResult.properties[DEDUPE_PROPERTY3];
      console.log(`running`)
      console.log(`Looking for duplicates based on ${DEDUPE_PROPERTY1} = ${dedupePropValue1} && ${DEDUPE_PROPERTY2} = ${dedupePropValue2} && ${DEDUPE_PROPERTY3} = ${dedupePropValue3}`);
  });
};

 

 

 

Also am I missing something, or is there zero documentation covering all the available objects, functions and properties accessible via Javascript? The API documentation is obviously quite different... unless I'm a complete muppet. 

0 Upvotes
2 Accepted solutions
sMoyse
Solution
Contributor

Custom Code Action Issue - contact property returning undefined

SOLVE

I've got futher along by taking a different approach with the property values, since I don't really see the need to get the contact object and interrogate the properties that way, when they are immediately available to me do to contact enrollment in the workflow. 

So I'm pulling them using `event.inputFields`

 

I then pass the 3 property names and their values as 3 different search filter groups. However, the next 4 lines of code after that throw an undefined error again. Since I can't tell in this code editor what has actually been returned by the search it's hard to tell what's wrong. 

/**
 * Searches for another contact with the same value of DEDUPE_PROPERTY.
 * - If no matches are found, nothing happens
 * - If one match is found, the enrolled contact is merged into the matching contact
 * - If more than one match is found, the action fails
 */

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

  const DEDUPE_PROPERTY1 = 'firstname';
  const DEDUPE_PROPERTY2 = 'lastname';
  const DEDUPE_PROPERTY3 = 'company';
  const PROPERTY_USED_TO_DEDUPE_CONTACTS = 'phone';

exports.main = (event, callback) => {
  // Make sure to add your API key under "Secrets" above.
  const hubspotClient = new hubspot.Client({
    accessToken: process.env.mContact
  });

  hubspotClient.crm.contacts.basicApi
    .getById(event.object.objectId, ['email'])
    .then(contactResult => {

    const firstNameVal = event.inputFields.firstname;
    const lastNameVal = event.inputFields.lastname;
    const companyNameVal = event.inputFields.company;

    console.log(`Looking for duplicates based on ${DEDUPE_PROPERTY1} = ${firstNameVal} && ${DEDUPE_PROPERTY2} = ${lastNameVal} && ${DEDUPE_PROPERTY3} = ${companyNameVal}`);
      hubspotClient.crm.contacts.searchApi
        .doSearch({
          filterGroups: [{
            filters: [
              {
                propertyName: 'firstname',
                operator: 'EQ',
                value: firstNameVal
              },
              {
                propertyName: 'lastname',
                operator: 'EQ',
                value: lastNameVal
              },
              {
                propertyName: 'company',
                operator: 'EQ',
                value: companyNameVal
              }
            ]
          }]
        })
        .then(searchResults => {
          let idsToMerge = searchResults.body.results
            .map(object => object.id)
            .filter(vid => Number(vid) !== Number(event.object.objectId));
	});
  });
};

 

This is the error returned:

2024-04-20T05:27:56.674Z	INFO	Looking for duplicates based on firstname = Taylor && lastname = Newman && company = Flight Digital
2024-04-20T05:27:56.897Z	ERROR	Unhandled Promise Rejection 	{"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"TypeError: Cannot read properties of undefined (reading 'results')","reason":{"errorType":"TypeError","errorMessage":"Cannot read properties of undefined (reading 'results')","stack":["TypeError: Cannot read properties of undefined (reading 'results')","    at /var/task/file.js:53:47","    at processTicksAndRejections (node:internal/process/task_queues:96:5)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: TypeError: Cannot read properties of undefined (reading 'results')","    at process.<anonymous> (file:///var/runtime/index.mjs:1276:17)","    at process.emit (node:events:513:28)","    at emit (node:internal/process/promises:140:20)","    at processPromiseRejections (node:internal/process/promises:274:27)","    at processTicksAndRejections (node:internal/process/task_queues:97:32)"]}
Unknown application error occurred
Runtime.Unknown

 

Those filter settings should be returning two contacts in the results:

SMoyse_1-1713590971052.png

 

View solution in original post

0 Upvotes
sMoyse
Solution
Contributor

Custom Code Action Issue - contact property returning undefined

SOLVE

Changing 

let idsToMerge = searchResults.body.results

to 

let idsToMerge = searchResults.results

fixed this issue.

The rest of my problems with async problems.... so I got rid of the .then approach and replaced it with await.

View solution in original post

0 Upvotes
3 Replies 3
sMoyse
Solution
Contributor

Custom Code Action Issue - contact property returning undefined

SOLVE

I've got futher along by taking a different approach with the property values, since I don't really see the need to get the contact object and interrogate the properties that way, when they are immediately available to me do to contact enrollment in the workflow. 

So I'm pulling them using `event.inputFields`

 

I then pass the 3 property names and their values as 3 different search filter groups. However, the next 4 lines of code after that throw an undefined error again. Since I can't tell in this code editor what has actually been returned by the search it's hard to tell what's wrong. 

/**
 * Searches for another contact with the same value of DEDUPE_PROPERTY.
 * - If no matches are found, nothing happens
 * - If one match is found, the enrolled contact is merged into the matching contact
 * - If more than one match is found, the action fails
 */

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

  const DEDUPE_PROPERTY1 = 'firstname';
  const DEDUPE_PROPERTY2 = 'lastname';
  const DEDUPE_PROPERTY3 = 'company';
  const PROPERTY_USED_TO_DEDUPE_CONTACTS = 'phone';

exports.main = (event, callback) => {
  // Make sure to add your API key under "Secrets" above.
  const hubspotClient = new hubspot.Client({
    accessToken: process.env.mContact
  });

  hubspotClient.crm.contacts.basicApi
    .getById(event.object.objectId, ['email'])
    .then(contactResult => {

    const firstNameVal = event.inputFields.firstname;
    const lastNameVal = event.inputFields.lastname;
    const companyNameVal = event.inputFields.company;

    console.log(`Looking for duplicates based on ${DEDUPE_PROPERTY1} = ${firstNameVal} && ${DEDUPE_PROPERTY2} = ${lastNameVal} && ${DEDUPE_PROPERTY3} = ${companyNameVal}`);
      hubspotClient.crm.contacts.searchApi
        .doSearch({
          filterGroups: [{
            filters: [
              {
                propertyName: 'firstname',
                operator: 'EQ',
                value: firstNameVal
              },
              {
                propertyName: 'lastname',
                operator: 'EQ',
                value: lastNameVal
              },
              {
                propertyName: 'company',
                operator: 'EQ',
                value: companyNameVal
              }
            ]
          }]
        })
        .then(searchResults => {
          let idsToMerge = searchResults.body.results
            .map(object => object.id)
            .filter(vid => Number(vid) !== Number(event.object.objectId));
	});
  });
};

 

This is the error returned:

2024-04-20T05:27:56.674Z	INFO	Looking for duplicates based on firstname = Taylor && lastname = Newman && company = Flight Digital
2024-04-20T05:27:56.897Z	ERROR	Unhandled Promise Rejection 	{"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"TypeError: Cannot read properties of undefined (reading 'results')","reason":{"errorType":"TypeError","errorMessage":"Cannot read properties of undefined (reading 'results')","stack":["TypeError: Cannot read properties of undefined (reading 'results')","    at /var/task/file.js:53:47","    at processTicksAndRejections (node:internal/process/task_queues:96:5)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: TypeError: Cannot read properties of undefined (reading 'results')","    at process.<anonymous> (file:///var/runtime/index.mjs:1276:17)","    at process.emit (node:events:513:28)","    at emit (node:internal/process/promises:140:20)","    at processPromiseRejections (node:internal/process/promises:274:27)","    at processTicksAndRejections (node:internal/process/task_queues:97:32)"]}
Unknown application error occurred
Runtime.Unknown

 

Those filter settings should be returning two contacts in the results:

SMoyse_1-1713590971052.png

 

0 Upvotes
sMoyse
Solution
Contributor

Custom Code Action Issue - contact property returning undefined

SOLVE

Changing 

let idsToMerge = searchResults.body.results

to 

let idsToMerge = searchResults.results

fixed this issue.

The rest of my problems with async problems.... so I got rid of the .then approach and replaced it with await.

0 Upvotes
sMoyse
Contributor

Custom Code Action Issue - contact property returning undefined

SOLVE

If I add a callback to the end of the code, then all the values return as expected:

    callback({
      outputFields: {
        firstname: event.inputFields.firstname,
        lastname: event.inputFields.laststname,
        company: event.inputFields.company,
        email: event.inputFields.email
      }
    });

SMoyse_0-1713587853515.png

I'm guessing there is something wrong with this code `

contactResult.properties

But it works in the dedupe by phone number sample.

I've been assuming this block of code returns the Contact Object itself and then I can interrogate it's properties, but maybe that isn't what's happening.

  hubspotClient.crm.contacts.basicApi
    .getById(event.object.objectId, ['email'])
    .then(contactResult => {}
0 Upvotes