bulk deleting associated emails from a company record

Hi,

Im trying to bulk remove the associtaed emails from a company record as we have hit the 50000 limit, im usuing the following code but cant seem to get it to work correctly,

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

exports.main = async (event) => {
const token = process.env.Company_token;
const companyId = event.inputFields.hs_object_id;
console.log(‘Using company ID:’, companyId);

// Initialize the HubSpot client
const hubspotClient = new hubspot.Client({ accessToken: token });

// Step 1: Get all engagements associated with the company
async function getEngagementsForCompany(companyId) {
try {
const response = await hubspotClient.crm.objects.searchApi.doSearch(‘engagements’, {
filterGroups: [{
filters: [{
propertyName: ‘associations.company’,
operator: ‘EQ’,
value: companyId
}]
}],
properties: [‘email.id’], //email ID
});

console.log(‘Using emailid:’, email.id);

// Step 2: Delete the association between the email and the company
async function deleteAssociation(emailId, companyId) {
const associationTypeId = ‘engagement_to_company’; // Replace with the actual association type ID if different

try {
await hubspotClient.apiRequest({
method: ‘DELETE’,
path: `/crm/v3/objects/emails/${emailId}/associations/company/${companyId}/${associationTypeId}`,
headers: {
‘Authorization’: `Bearer ${token}`,
‘Content-Type’: ‘application/json’,
}
});
console.log(`Successfully deleted association for email ${emailId} with company ${companyId}`);
} catch (error) {
console.error(`Error deleting association: ${error.response?.status} - ${error.message}`);
}
}

// Step 3: Main function to process email unassociation
async function removeEmailAssociationsFromCompany(companyId) {
const engagements = await getEngagementsForCompany(companyId);

for (const engagement of engagements) {
const engagementId = engagement.id;
const engagementType = engagement.properties?.[‘engagement.type’];
const emailId = engagement.properties?.[‘email.id’]; // Extract email ID

// Log engagement details for debugging
console.log(`Processing engagement ${engagementId} with type ${engagementType} and email ID ${emailId}`);

// Only handle email engagements and ensure email ID is present
if (engagementType === ‘EMAIL’ && emailId) {
await deleteAssociation(emailId, companyId);
}
}
}

// Execute the script
await removeEmailAssociationsFromCompany(companyId);
};

Any ideas?

Hey, @MatBehr :waving_hand: Can you tell our community more about where your code is breaking? Does it partially work? Or is it throwing errors immediately? Also, can you share the full error messages you get when running this code, please?

Thanks! — Jaycee

Hi,

Error is as follows,

WARNING: The logs for this function have exceeded the 4KB limit.

2024-09-19T08:23:08.451Z undefined ERROR Uncaught Exception {“errorType”:“Runtime.UserCodeSyntaxError”,“errorMessage”:“SyntaxError: Missing catch or finally after try”,“stack”:[“Runtime.UserCodeSyntaxError: SyntaxError: Missing catch or finally after try”," at _loadUserApp (file:///var/runtime/index.mjs:1084:17)“,” at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1119:21)“,” at async start (file:///var/runtime/index.mjs:1282:23)“,” at async file:///var/runtime/index.mjs:1288:1"]}
INIT_REPORT Init Duration: 154.51 ms Phase: init Status: error Error Type: Runtime.UserCodeSyntaxError
2024-09-19T08:23:09.568Z undefined ERROR Uncaught Exception {“errorType”:“Runtime.UserCodeSyntaxError”,“errorMessage”:“SyntaxError: Missing catch or finally after try”,“stack”:[“Runtime.UserCodeSyntaxError: SyntaxError: Missing catch or finally after try”," at _loadUserApp (file:///var/runtime/index.mjs:1084:17)“,” at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1119:21)“,” at async start (file:///var/runtime/index.mjs:1282:23)“,” at async file:///var/runtime/index.mjs:1288:1"]}
INIT_REPORT Init Duration: 1359.27 ms Phase: invoke Status: error Error Type: Runtime.UserCodeSyntaxError
START RequestId: 114a2668-2bb0-43e2-9b5e-52ba7bed1b58 Version: $LATEST

Memory: 65/128 MB
Runtime: 1369.92 ms

All im really trying to do, is find all email engagements that are associated to the enrolled company and delete the asociation as we have hit the 50000 email to company associtaion limit but emails dont need to be associated with the company