Configuring a polling event source to send push notifications
AntonAleksandrov 270005D80F Visits (10229)
Worklight adapter framework allows to implement event sources. Event source are used to generate notification events that WL client framework can subscribe to, e.g. push notifications. However in order to send a notification one must be retrieved from a backend first. Event source can either poll notifications from the back-end system, or wait for the back-end system to explicitly push a new notification.
You can read more about event sources and push notifications in the Push Notifications training module -
In this post I'll focus on creating a polling event source and using it to send push notifications.
Polling event source is a long running periodical task with following mandatory properties
Below is a sample of a basic polling event source:
The code above creates a polling event source. doSomething() function will be invoked every three seconds. If you deploy this adapter to Worklight server and observe the server console you'll see below logs:
Note that polling will not start instantly once you deploy the adapter but after several seconds. Also note that doSomething() function is invoked with a three seconds interval - exactly as expected.
Now, lets see a more realistic example of using a polling event source
In the above sample polling event source continuously invokes sendNotifications() function with a 3 seconds interval.
Every time sendNotification() function is invoked is requests messages data from backend (lines 18-19). In the sample above I'm assuming a HTTP backend, but it can be any other type of backend Worklight adapter support, e.g. SQL, MQ etc. The code assumes that the following JSON is returned by a backend. However, since Worklight adapter knows how to automatically convert data to JSON, it can also be XML.
text: "New incoming transition",
text: "Please approve withdrawal",
Next the code is iterating over received messages array (line 22). Every single message (line 25) contains userId of a user that the notification should be sent to. Using this userId the code tries to obtain a userSubscription object (line28). In case userSubscription is found for specified userId (line 30) - new notification is created (line 32) and sent to all user devices (line 33). In case userSubscription for specified userId was not found - an error is logged (line 35)
Important thing to remember is that unlike regular adapter procedures the polling function is triggered by a Worklight Server itself and not by the incoming request. Therefore any data or APIs related to request or session context will not be available or functional, e.g. APIs like WL.S