Skip to content

Instantly share code, notes, and snippets.

@vinhhungle
Last active November 25, 2018 10:46
Show Gist options
  • Save vinhhungle/55fe0c5d1eb9b06dcfa14f82bef47cea to your computer and use it in GitHub Desktop.
Save vinhhungle/55fe0c5d1eb9b06dcfa14f82bef47cea to your computer and use it in GitHub Desktop.
Salesforce Streaming API Test

Open Dev Console > Debug > Open Execute Anonymous Window

Execute the codes below:

PushTopic pushTopic = new PushTopic();
pushTopic.ApiVersion = 37.0;
pushTopic.Name = 'AllAccounts';
pushTopic.Description = 'All records for the Account object';
pushtopic.Query = 'SELECT Id, Name FROM Account';
insert pushTopic;

Confirm topic has been created by executing this query in Query Editor:

SELECT Id,Name FROM PushTopic WHERE Name='AllAccount'

Simple Test For Salesforce Streaming API Outside Salesforce

Use jsforce ajax proxy

Add these libs to the page:

<script src="streaming/org/cometd.js"></script>
<script src="streaming/jquery-1.5.1.js"></script>
<script src="streaming/json2.js"></script>
<script src="streaming/jquery.cometd.js"></script>

<script src="libs/jsforce-core.js"></script>
<script src="libs/jsforce-api-apex.min.js"></script>

Authenticate with Salesforce using OAuth2

jsforce.browser.init({
    clientId: 'SALESFORCE_CONNECTED_APP_ID',
    redirectUri: 'http://localhost:8200/oauthcallback.html',
    proxyUrl: 'http://localhost:8200/proxy/'
});

jsforce.browser.on('connect', function(conn) {
    
    console.log('connection', conn);
    document.cookie = 'BAYEUX_BROWSER=; path=/cometd';

    $.cometd.init({
        url: 'http://localhost:8200/cometd/37.0/',
        requestHeaders: { 
          Authorization: 'OAuth ' + conn.accessToken, 
          'salesforceproxy-endpoint': conn.instanceUrl + '/cometd/37.0/'
        }
    });

    $.cometd.subscribe('/topic/AllAccounts', function(message) {
        console.log('Account changed: ', message)
    });
    
    setTimeout(function() {
      conn.sobject("Account").create([
        { Name : 'My Account #1' },
        { Name : 'My Account #2' }
      ]);
      // output 2 messages 'Account changed: ' and event objects
    }, 3000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment