APIs & Integrations

DZoladz36
Participant | Elite Partner
Participant | Elite Partner

Custom Object Code Issue

SOLVE

Hi all, I built a custom object that records activites (page view, form submission, ad submission, etc) I created the custom object to store some of these native activites along with other custom events not native in HubSpot, to use in journey mapping. The client wants to identify the first activity based on the activity (event) date. So as these records are created, I created a workflow with the following code to mark (check) if the event was the first (custom property called "First Scoring Event". The logic is if no other event record exists assocated to the contact then set First Scoing Event to true. If there is a an exisisting record then do nothing. I created a workflow to populate another event record custome property call Associated contact ID. The workflow copies the Contact Record ID to the associated event record property. The code below works in setting the first record First Scoring Record to true but when another record is created, it can't find any other records associated to the same contact, thus changes the First Scoring Record to true on the second record when it should do nothing. Can anyone see what I'm missing? Thanks!

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

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

const OBJECT_TYPE_ID = '2-44054457';
const PROPERTY = 'associated_contact_id';

const scoringEventId = (event.inputFields['hs_object_id'] || '').trim();
const contactId = (event.inputFields[PROPERTY] || '').trim();

if (!scoringEventId || !contactId) {
console.log(' Missing scoringEventId or associated_contact_id. Exiting.');
return callback({ outputFields: {} });
}

console.log(`🔍 Checking if any scoring event already exists with ${PROPERTY} = ${contactId}`);

try {
const response = await hubspotClient.crm.objects.basicApi.getPage(
OBJECT_TYPE_ID,
100,
undefined,
[PROPERTY]
);

const events = response.results || [];

events.forEach(e => {
console.log(`🧪 Event ${e.id} → ${PROPERTY}: ${e.properties[PROPERTY]}`);
});

const match = events.find(e =>
String(e.id) !== scoringEventId &&
String(e.properties[PROPERTY] || '').trim() === contactId
);

if (match) {
console.log(`⚠️ Another event exists for contact ${contactId} — skipping update`);
return callback({ outputFields: {} });
}

await hubspotClient.crm.objects.basicApi.update(OBJECT_TYPE_ID, scoringEventId, {
properties: {
first_scoring_event: true
}
});

console.log(` Marked event ${scoringEventId} as first_scoring_event = true`);
callback({ outputFields: {} });

} catch (err) {
console.error('🚨 Error during update:', err.response?.body || err.message || err);
callback({ outputFields: {} });
}
};



0 Upvotes
1 Accepted solution
sylvain_tirreau
Solution
Top Contributor

Custom Object Code Issue

SOLVE

Hi @DZoladz36 ,

 

const response = await hubspotClient.crm.objects.basicApi.getPage(
      OBJECT_TYPE_ID,
      100,
      undefined,
      [PROPERTY]
    );

In this snippet of code, you only retrieve the last 100 events without navigating through all the pages: if between the contact's first event and the second, 100 events were created for all contacts combined, your first event will no longer be visible. You have to navigate through all the pages, but it's time-consuming.

 

There's a more efficient way to do what you want: retrieve only the events related to your current contact.

 

For example (untested code):

    const searchRequest = {
      filterGroups: [{
        filters: [{
          propertyName: PROPERTY,
          operator: 'EQ',
          value: contactId
        }, {
          propertyName: 'hs_object_id',
          operator: 'NEQ',
          value: scoringEventId
        }]
      }],
      limit: 1
    };

    const { total } = await hubspotClient.crm.objects.searchApi.doSearch(
      OBJECT_TYPE_ID,
      searchRequest
    );
    
    if (total > 0) {
      console.log(`Event exists for the contact ${contactId}`);
      return callback({ outputFields: {} });
    }

, but it's time-consuming 

View solution in original post

0 Upvotes
2 Replies 2
sylvain_tirreau
Solution
Top Contributor

Custom Object Code Issue

SOLVE

Hi @DZoladz36 ,

 

const response = await hubspotClient.crm.objects.basicApi.getPage(
      OBJECT_TYPE_ID,
      100,
      undefined,
      [PROPERTY]
    );

In this snippet of code, you only retrieve the last 100 events without navigating through all the pages: if between the contact's first event and the second, 100 events were created for all contacts combined, your first event will no longer be visible. You have to navigate through all the pages, but it's time-consuming.

 

There's a more efficient way to do what you want: retrieve only the events related to your current contact.

 

For example (untested code):

    const searchRequest = {
      filterGroups: [{
        filters: [{
          propertyName: PROPERTY,
          operator: 'EQ',
          value: contactId
        }, {
          propertyName: 'hs_object_id',
          operator: 'NEQ',
          value: scoringEventId
        }]
      }],
      limit: 1
    };

    const { total } = await hubspotClient.crm.objects.searchApi.doSearch(
      OBJECT_TYPE_ID,
      searchRequest
    );
    
    if (total > 0) {
      console.log(`Event exists for the contact ${contactId}`);
      return callback({ outputFields: {} });
    }

, but it's time-consuming 

0 Upvotes
BérangèreL
Community Manager
Community Manager

Custom Object Code Issue

SOLVE

Hi @DZoladz36, I hope that you are well!
 

Thanks for asking the HubSpot Community!

Here is a documentation on the topic "Timeline Events", just for information.

Also, I'd love to invite our Top Experts and Community Members to join this discussion: Hi @Anton, @sylvain_tirreau, @zach_threadint and @Jarro do you have any tips to share with @DZoladz36, please?

Have a beautiful day and thanks so much for your help! ❤️
Bérangère


HubSpot’s AI-powered customer agent resolves up to 50% of customer queries instantly, with some customers reaching up to 90% resolution rates.
Learn More.


Saviez vous que la Communauté est disponible en français?
Rejoignez les discussions francophones en changeant votre langue dans les paramètres! !
0 Upvotes