Node.js Examples

JavaScript

Complete Node.js examples for integrating with the Magnetite API

Installation

First, install the required dependencies:

npm install axios dotenv

Basic Setup

Create a basic client for interacting with the Magnetite API:

// magnetite-client.js
const axios = require('axios');
require('dotenv').config();

class MagnetiteClient {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseURL = 'https://magnetite.ai/api';
    this.client = axios.create({
      baseURL: this.baseURL,
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      }
    });
  }

  async addLeadToCampaign(campaignId, leadData) {
    try {
      const response = await this.client.post(`/campaigns/${campaignId}/leads`, leadData);
      return response.data;
    } catch (error) {
      throw this.handleError(error);
    }
  }

  async addLeadsInBulk(campaignId, leads) {
    const results = [];

    for (const lead of leads) {
      try {
        const result = await this.addLeadToCampaign(campaignId, lead);
        results.push({ lead, success: true, result });

        // Brief delay between requests to respect rate limits
        await this.sleep(1000);
      } catch (error) {
        results.push({ lead, success: false, error: error.message });
      }
    }

    return results;
  }

  handleError(error) {
    if (error.response) {
      return new Error(`API Error: ${error.response.data.error || error.response.statusText}`);
    } else if (error.request) {
      return new Error('Network Error: No response received from server');
    } else {
      return new Error(`Request Error: ${error.message}`);
    }
  }

  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

module.exports = MagnetiteClient;

Environment Variables

Create a .env file to store your API credentials:

# .env
MAGNETITE_API_KEY=sk_your_api_key_here
MAGNETITE_CAMPAIGN_ID=your_campaign_id_here

Complete Examples

Add a Single Lead
Simple example of adding a lead to your campaign
// add-lead.js
const MagnetiteClient = require('./magnetite-client');

async function addLeadExample() {
  const client = new MagnetiteClient(process.env.MAGNETITE_API_KEY);

  try {
    const result = await client.addLeadToCampaign(
      process.env.MAGNETITE_CAMPAIGN_ID,
      {
        companyName: 'Acme Corp',
        contactName: 'John Smith',
        email: 'john@acme.com',
        title: 'VP of Sales',
        domain: 'acme.com',
        linkedInUrl: 'https://linkedin.com/in/johnsmith',
        notes: 'Met at SaaStr conference'
      }
    );

    console.log('Lead added successfully!');
    console.log('Prospect ID:', result.prospectId);
    console.log('Status:', result.status);
    console.log('Message:', result.message);

    return result;
  } catch (error) {
    console.error('Error adding lead:', error.message);
    throw error;
  }
}

addLeadExample()
  .then(() => console.log('Done!'))
  .catch(console.error);
Add Lead with Enrichment Data
Pass pre-enriched company and contact data for faster processing
// add-enriched-lead.js
const MagnetiteClient = require('./magnetite-client');

async function addEnrichedLead() {
  const client = new MagnetiteClient(process.env.MAGNETITE_API_KEY);

  try {
    const result = await client.addLeadToCampaign(
      process.env.MAGNETITE_CAMPAIGN_ID,
      {
        // Required fields
        companyName: 'TechCorp Inc',
        contactName: 'Jane Doe',
        email: 'jane@techcorp.com',

        // Optional basic fields
        title: 'Marketing Director',
        domain: 'techcorp.com',
        phone: '+1-555-123-4567',
        linkedInUrl: 'https://linkedin.com/in/janedoe',
        companyLinkedInUrl: 'https://linkedin.com/company/techcorp',
        notes: 'Referred by partner XYZ',

        // Pre-enriched company data (optional)
        company: {
          industry: 'Technology',
          employeeCount: 250,
          revenue: '$50M-100M',
          fundingStage: 'Series B',
          technologies: ['React', 'Node.js', 'AWS'],
          description: 'Enterprise SaaS platform'
        },

        // Pre-enriched contact data (optional)
        contact: {
          bio: 'Marketing leader with 10+ years experience',
          seniority: 'Director',
          department: 'Marketing',
          city: 'San Francisco',
          state: 'CA',
          country: 'USA'
        },

        // Extra context for research agent (optional)
        extraContext: {
          meetingNotes: 'Discussed integration needs',
          painPoints: ['Lead generation', 'Sales automation'],
          referredBy: 'Partner program'
        }
      }
    );

    console.log('Enriched lead added!');
    console.log('Result:', JSON.stringify(result, null, 2));

  } catch (error) {
    console.error('Error:', error.message);
    throw error;
  }
}

addEnrichedLead()
  .then(() => console.log('Done!'))
  .catch(console.error);
Bulk Lead Import
Import multiple leads with rate limiting
// bulk-import.js
const MagnetiteClient = require('./magnetite-client');

async function bulkImport() {
  const client = new MagnetiteClient(process.env.MAGNETITE_API_KEY);

  const leads = [
    {
      companyName: 'StartupCo',
      contactName: 'Sarah Johnson',
      email: 'sarah@startupco.com',
      title: 'CEO'
    },
    {
      companyName: 'BigCorp Industries',
      contactName: 'Michael Chen',
      email: 'michael@bigcorp.com',
      title: 'Sales Director'
    },
    {
      companyName: 'MidSize Solutions',
      contactName: 'Emily Rodriguez',
      email: 'emily@midsize.com',
      title: 'VP of Marketing'
    }
  ];

  console.log(`Importing ${leads.length} leads to campaign...`);

  const results = await client.addLeadsInBulk(
    process.env.MAGNETITE_CAMPAIGN_ID,
    leads
  );

  // Summary
  const successful = results.filter(r => r.success);
  const failed = results.filter(r => !r.success);

  console.log('\n=== IMPORT SUMMARY ===');
  console.log('Total processed:', results.length);
  console.log('Successful:', successful.length);
  console.log('Failed:', failed.length);

  if (failed.length > 0) {
    console.log('\nFailed leads:');
    failed.forEach(f => {
      console.log(`  - ${f.lead.email}: ${f.error}`);
    });
  }

  return results;
}

bulkImport()
  .then(() => console.log('\nBulk import complete!'))
  .catch(console.error);
Express.js Webhook Receiver
Handle meeting booked webhooks from Magnetite
// webhook-server.js
const express = require('express');
const app = express();

app.use(express.json());

// Webhook endpoint for meeting booked events
app.post('/webhooks/magnetite', (req, res) => {
  const event = req.body;

  console.log('Received webhook:', event.event);

  if (event.event === 'meeting_booked') {
    const { prospect, meeting, campaignId } = event;

    console.log('Meeting booked!');
    console.log('Company:', prospect.companyName);
    console.log('Contact:', prospect.contactName);
    console.log('Email:', prospect.email);
    console.log('Scheduled:', meeting.scheduledAt);
    console.log('Duration:', meeting.duration, 'minutes');

    // Handle the meeting booking
    // - Update your CRM
    // - Send notifications
    // - Create calendar events
    // etc.

    // Example: Send to Slack
    // await notifySlack(prospect, meeting);
  }

  res.json({ received: true });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Webhook server running on port ${PORT}`);
});

Next Steps

Explore more examples in different programming languages.