Streaming API is the best way to post events based on any changes to the data which matches your defined SOQL query. These events can be handled within Salesforce or outside Salesforce using Bayeux Protocol and CometD. It can listen to:
- New Record (Created)
Below are the generic steps that you need to follow to create a PushTopic which will have you streaming channel name where you can publish your events:
- Create a PushTopic based on a SOQL query. This defines the channel.
- Clients subscribe to the channel.
- A record is created, updated, deleted, or undeleted (an event occurs). The changes to that record are evaluated.
- If the record changes match the criteria of the PushTopic query, a notification is generated by the server and received by the subscribed clients.
In this post, we will learn how you can subscribe to a PushTopic and listen for the events using cometD js library We will be creating an account spy app which will listen to the changes on account records and display in the browser console.
Create A PushTopic
Run below code snippet in your developer console anonymous window.
Create this lighting event, which will be fired by your generic streaming api handler component and will pass the data to the parent component. It takes complete message payload as an attribute.
This would be a generic component that you can use with any of your component where you want to listen for events. It accepts “channel name” as an attribute.
All your logic to connect, subscriber and unsubscriber to a channel will go here.
Create Server Controller StreamingApiController.apxc
This server controller will pass the current user’s session if to “StreamingApiHandler.cmp” generic component. The session id will be used to make a connection to Salesforce server using oAuth.
This would be the parent component, which will use the StreamingApiHandler.cmp component to listen for the events. You can replace this component with your own functionality or custom component.
Below sample payload is an example of payload received from Streaming Api event which you can handle as per your requirement.
Once all the code is written, add your AccountSpy component somewhere(maybe using AppBuilder) and keep that page open. You will be below console logs whenever changes will happen in an Account record.
That’s it, now you have your own generic StreamingApiHandler component which you can use with any of your components to listen to Streaming Api events.
Please do comment on this post to share your review or feedback