Lightyear LogoLightyear Docs

Step 6 - Create the command-line script

Let's build a Node.js script that uses the Lightyear API to interact with HubSpot.

Script overview

Our script will:

  1. Connect to the Lightyear API
  2. Retrieve the HubSpot access token for our managed user
  3. Prompt for a company name
  4. Create the company in HubSpot
  5. Display the results

Set up the project

First, create a new directory for your script:

mkdir hubspot-lightyear-script
cd hubspot-lightyear-script
npm init -y

Write the script

Create a file called create-hubspot-company.js:

#!/usr/bin/env node
 
const readline = require("readline");
const https = require("https");
 
// Configuration
const LIGHTYEAR_API_KEY = process.env.LIGHTYEAR_API_KEY;
const LIGHTYEAR_API_URL =
  process.env.LIGHTYEAR_API_URL || "https://api.lightyear.dev";
const MANAGED_USER_ID = "hubspot-test-user"; // The external ID we used earlier
 
if (!LIGHTYEAR_API_KEY) {
  console.error("Please set LIGHTYEAR_API_KEY environment variable");
  process.exit(1);
}
 
// Create readline interface for user input
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
 
// Function to make API requests
function makeRequest(options, data = null) {
  return new Promise((resolve, reject) => {
    const req = https.request(options, (res) => {
      let body = "";
      res.on("data", (chunk) => (body += chunk));
      res.on("end", () => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(JSON.parse(body));
        } else {
          reject(new Error(`Request failed: ${res.statusCode} - ${body}`));
        }
      });
    });
 
    req.on("error", reject);
 
    if (data) {
      req.write(JSON.stringify(data));
    }
 
    req.end();
  });
}
 
// Function to get the access token for our managed user
async function getAccessToken() {
  const options = {
    hostname: new URL(LIGHTYEAR_API_URL).hostname,
    path: `/api/managed-users/${MANAGED_USER_ID}/integrations/hubspot/auth`,
    method: "GET",
    headers: {
      Authorization: `Bearer ${LIGHTYEAR_API_KEY}`,
      "Content-Type": "application/json",
    },
  };
 
  const response = await makeRequest(options);
  return response.accessToken;
}
 
// Function to create a company in HubSpot
async function createCompany(accessToken, companyName) {
  const options = {
    hostname: "api.hubapi.com",
    path: "/crm/v3/objects/companies",
    method: "POST",
    headers: {
      Authorization: `Bearer ${accessToken}`,
      "Content-Type": "application/json",
    },
  };
 
  const data = {
    properties: {
      name: companyName,
      domain: `${companyName.toLowerCase().replace(/\s+/g, "-")}.com`,
    },
  };
 
  return await makeRequest(options, data);
}
 
// Main function
async function main() {
  try {
    console.log("🚀 HubSpot Company Creator via Lightyear\n");
 
    // Get the access token
    console.log("Getting HubSpot access token...");
    const accessToken = await getAccessToken();
    console.log("✅ Access token retrieved\n");
 
    // Prompt for company name
    rl.question("Enter company name: ", async (companyName) => {
      try {
        console.log(`\nCreating company "${companyName}" in HubSpot...`);
 
        const company = await createCompany(accessToken, companyName);
 
        console.log("\n✅ Company created successfully!");
        console.log(`Company ID: ${company.id}`);
        console.log(`Company Name: ${company.properties.name}`);
        console.log(`Domain: ${company.properties.domain}`);
      } catch (error) {
        console.error("\n❌ Error creating company:", error.message);
      } finally {
        rl.close();
      }
    });
  } catch (error) {
    console.error("❌ Error:", error.message);
    rl.close();
  }
}
 
// Run the script
main();

Understanding the code

Let's break down the key parts:

Configuration

  • We read the Lightyear API key from environment variables
  • The managed user ID matches what we created earlier
  • We default to Lightyear's production API URL

Getting the access token

async function getAccessToken() {
  // Call Lightyear API to get HubSpot credentials
  // Returns the access token for the managed user
}

This function retrieves the HubSpot access token that Lightyear is storing for our managed user.

Creating a company

async function createCompany(accessToken, companyName) {
  // Direct call to HubSpot API
  // Uses the access token from Lightyear
}

This makes a direct API call to HubSpot using the retrieved access token.

Error handling

The script includes proper error handling for:

  • Missing API keys
  • Network failures
  • API errors
  • Invalid responses

What's next?

Great! You've written the script. Now let's run it and see it in action!

On this page