Subscribe to Salesforce Streaming Api in NodeJs

Salesforce streaming Api is an application programming interface. Hard to argue about that. But it’s not the Restful Api or SOAP api we know. It’s better because it allows us to sync whatever happened in Salesforce to wherever you want in almost real-time. Yes, Salesforce calls it Api but in fact, streaming Api is an enterprise service bus similar to Apache Camel, Kafa and Azure Service Bus. It’s a pub-sub model. The nodejs code below demo how to subscribe to all CDC (capture data change) events in Salesforce.

(function() {
    var jsforce = require('jsforce');

    const url = 'https://um1.lightning.force.com/cometd/48.0/';
    const channel = '/data/ChangeEvents';

    console.log('Setting up jsforce...');

    const sfconn = new jsforce.Connection({
        oauth2: {
            clientId: '<your client Id>',
            clientSecret: '<your client secret>',
            redirectUrl: '<your redirect url>'
        }
    });

    console.log('Acquiring SF session Id...');

    sfconn.login('<your SF username>', '<your SF password>', function(err, userInfo) {
        console.log('SF session id acquired: ' + sfconn.accessToken);
        sfconn.streaming.topic(channel).subscribe(function(message) {
            console.log(JSON.stringify(message));
        });
    });
})();

The source code is also available in my github:

https://github.com/gaogang/salesforce-connect-ob-webjob

Obviously this simple piece of code only write the changes to the console but it opens up so many opportunities including my next topic – Mimicking Heroku connect in Azure. To be continue…

Leave a comment