Skip to content

Instantly share code, notes, and snippets.

@jackcoldrick90
Created May 19, 2021 12:13
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jackcoldrick90/9d7301deb5c3ff42b24d40a3cda46686 to your computer and use it in GitHub Desktop.
Save jackcoldrick90/9d7301deb5c3ff42b24d40a3cda46686 to your computer and use it in GitHub Desktop.
This is an example of a code snippet that checks to see if a contact exists in an external DB (MySQL). If it does we update a property to "true" otherwise "false".
// Import required libraries
const hubspot = require('@hubspot/api-client');
const mysql = require('mysql');
// This function is called when the custom coded action is executed
exports.main = (event, callback) => {
// Create a new instance of the HubSpot API Client - we need this to interact with the CRM APIs to retrieve information relating to the currently enrolled record
const hubspotClient = new hubspot.Client({
apiKey: process.env.HAPIKEY
});
// Get the email address of the currently enrolled contact using the CRM Contacts API - can specifcy additional properties to pull
hubspotClient.crm.contacts.basicApi.getById(event.object.objectId, ["email"])
.then(results => {
// Store the result in a variable - we'll use this in our SQL query
let emailAddress = results.body.properties.email;
// Create a mySQL connection - defining username, passowrd, host and DB using secrets
var con = mysql.createConnection({
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DB
});
//
con.connect(function (err) {
if (err) throw err;
console.log("Connected!"); // Debugging - will show in
var sql = "SELECT * FROM customers WHERE emailAddress = '" + emailAddress + "'"
con.query(sql, function (err, result) {
if (err) throw err;
// Check to see if any results returned
if (result.length > 0) { // RESULTS FOUND
console.log(result);
hubspotClient.crm.contacts.basicApi.update(event.object.objectId, {"properties":{"contact_found___mysql_db": true}});
} else { // NO RESULTS
console.log('no results found');
// set variable and pass to data output - if/then logic further in workflow...
hubspotClient.crm.contacts.basicApi.update(event.object.objectId, {"properties":{"contact_found___mysql_db": false}});
}
con.end(); // Terminate connection
});
});
callback({ outputFields: {} });
})
.catch(err => {
console.error(err);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment