How to publish Salesforce platform events from Salesforce API from Node.js

How to publish Salesforce platform events from Salesforce API from Node.js

Salesforce platform events from Salesforce API using Node.js, follow these steps:

Install the jsforce package, which provides a Salesforce API client for Node.js. You can use npm to install it by running the following command in your project directory:

npm install jsforce 

Use the following code as a starting point to connect to the Salesforce API and publish a platform event:

const jsforce = require('jsforce');

// Salesforce credentials 
const username = '<YOUR_SALESFORCE_USERNAME>';
const password = '<YOUR_SALESFORCE_PASSWORD>';
const securityToken = '<YOUR_SALESFORCE_SECURITY_TOKEN>';

// Salesforce connection 
const conn = new jsforce.Connection();

conn.login(username, password + securityToken, (err, userInfo) => {
    if (err) { 
        return console.error(err); 
    }

    console.log('Connected to Salesforce');

    // Define the platform event name and payload   
    const eventApiName = 'My_Platform_Event__e';
    const eventPayload = { field1: 'value1', field2: 'value2' };

    // Publish the platform event   
    conn.sobject(eventApiName).create(eventPayload, (err, res) => {
        if (err) { return console.error(err); }
        console.log('Platform event published:', res);
    });
});

Make sure to replace <YOUR_SALESFORCE_USERNAME>, <YOUR_SALESFORCE_PASSWORD>, and <YOUR_SALESFORCE_SECURITY_TOKEN> with your Salesforce credentials. Also, modify the eventApiName and eventPayload variables to match your platform event’s API name and desired payload.

Run the Node.js script, and if everything is configured correctly, it should connect to Salesforce and publish the platform event.

node publish-platform-event.js

By following these steps, you should be able to publish Salesforce platform events from Salesforce API using Node.js.