Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example HubSpot custom code action snippets
/**
* Capitalizes the first letter of every part of a contact's first and last name.
*
* Examples:
* - angus -> Angus
* - ANGUS A. -> Angus A.
* - O'connor -> O'Connor
*/
const FIRSTNAME_PROP = "firstname";
const LASTNAME_PROP = "lastname";
const hubspot = require('@hubspot/api-client');
exports.main = (event, callback) => {
callback(processEvent(event));
};
function processEvent(event) {
const hubspotClient = new hubspot.Client({ apiKey: process.env.HAPIKEY });
let contactId = event.object.objectId;
hubspotClient.crm.contacts.basicApi
.getById(contactId, [FIRSTNAME_PROP, LASTNAME_PROP])
.then(results => {
let firstname = results.body.properties[FIRSTNAME_PROP];
let lastname = results.body.properties[LASTNAME_PROP];
hubspotClient.crm.contacts.basicApi
.update(
contactId,
{
properties: {
[FIRSTNAME_PROP]: capitalizeName(firstname),
[LASTNAME_PROP]: capitalizeName(lastname)
}
}
)
.then(updateResults => null);
});
}
function capitalizeName(name) {
return name
.toLowerCase()
.trim()
.replace(/\b(\w)/g, s => s.toUpperCase());
}
/**
* Transforms a date string into a standard format.
*/
const DATE_PROP = "createdate";
const hubspot = require('@hubspot/api-client');
exports.main = (event, callback) => {
callback(processEvent(event));
};
function processEvent(event) {
const hubspotClient = new hubspot.Client({ apiKey: process.env.HAPIKEY });
let contactId = event.object.objectId;
hubspotClient.crm.contacts.basicApi
.getById(contactId, ['phone'])
.then(results => {
let dateString = results.body.properties[DATE_PROP];
hubspotClient.crm.contacts.basicApi
.update(
contactId,
{
properties: {
[DATE_PROP]: formatDate(dateString)
}
}
)
.then(updateResults => null);
});
}
function formatDate(dateString) {
let date = new Date(dateString);
let year = '' + date.getFullYear();
let month = '' + date.getMonth() + 1;
let day = '' + date.getDate();
if (month.length < 2) {
month = '0' + month;
}
if (day.length < 2) {
day = '0' + day;
}
// Format as MM/DD/YYYY
return month + '/' + day + '/' + year;
// Alternatives:
// - DD/MM/YYYY
// return day + '/' + month + '/' + year;
// - YYYY-MM-DD
// return year + '-' + month + '-' + day;
}
/**
* Transforms a 10-digit U.S. phone number into a standard format.
*/
const PHONE_NUMBER_PROP = "phone";
const hubspot = require('@hubspot/api-client');
exports.main = (event, callback) => {
callback(processEvent(event));
};
function processEvent(event) {
const hubspotClient = new hubspot.Client({ apiKey: process.env.HAPIKEY });
let contactId = event.object.objectId;
hubspotClient.crm.contacts.basicApi
.getById(contactId, [PHONE_NUMBER_PROP])
.then(results => {
let phone = results.body.properties[PHONE_NUMBER_PROP];
hubspotClient.crm.contacts.basicApi
.update(
contactId,
{
properties: {
[PHONE_NUMBER_PROP]: formatPhoneNumber(phone)
}
}
)
.then(updateResults => null);
});
}
function formatPhoneNumber(phoneNumber) {
let cleaned = phoneNumber.replace(/\D/g, '').trim();
let match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
if (match) {
// Format as (XXX) XXX-XXXX
return '(' + match[1] + ') ' + match[2] + '-' + match[3];
// Alternatives (match[1] is the first three digits,
// match[2] is the second three, match[3] is the last four):
// - XXX-XXX-XXXX
// return match[1] + '-' + match[2] + '-' + match[3];
}
return phoneNumber;
}
/**
* Selects a random owner ID with the given relative probability.
*
* To get an owner ID for your HubSpot users, go to Setting -> Properties then
* search for "Contact owner" and click "edit." The "owner ID" is the internal
* value for each user.
*
* To use this value in your workflow, make sure you add an output to your custom
* code action with a data type of "enumeration" and a name of "owner_id" (no quotes).
* Then you can use a "Copy property value" action to update the object owner to
* the user selected by this code.
*
* NOTE: since this is random, it is possible that the actual selections will
* not exactly match the given distribution (in the example, 40%/40%/20%).
* The more times the code is run, the closer it will be to the actual desired
* distribution (this is known as the "Law of Large Numbers"; see
* https://en.wikipedia.org/wiki/Law_of_large_numbers). *This should only be
* used in situations where it is acceptable if the actual selections are not
* exactly the chosen percentages!*
*/
// Edit percentages and owner IDs here
const owners = [
{
ownerId: 6090927,
percentage: 40
},
{
ownerId: 6305635,
percentage: 40
},
{
ownerId: 6305638,
percentage: 20
}
];
// Start of code
const Promise = require("bluebird");
const randomNumber = require("random-number-csprng");
exports.main = (event, callback) => {
let totalPercentage = 0;
owners.forEach(owner => totalPercentage += owner.percentage);
Promise
.try(() => randomNumber(1, totalPercentage))
.then(randomPercentage => {
let currentPercentage = 0;
let selectedOwnerId;
for (let i = 0; i < owners.length; i++) {
currentPercentage += owners[i].percentage;
if (currentPercentage >= randomPercentage) {
selectedOwnerId = owners[i].ownerId;
break;
}
}
console.log(`The random value was ${randomPercentage}, which corresponds to owner ID ${selectedOwnerId}`);
callback({
outputFields: {
owner_id: selectedOwnerId
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment