Add event-driven business logic

Sending and receiving messages is the foundation of PubNub but it's also just the beginning. Once you're able to send messages to where they need to go, you'll probably be wondering What else can I do with messages? This is where Functions come in.

Functions are JavaScript code that can be triggered before or after any event that happens in your PubNub environment. They can be programmed to run at specific intervals, or you can even create external requests to run the code in your function. Functions are event-driven, so all you need to bring is the code.

To create a function, head to the Admin Portal, select your keyset, and Functions. Give the name and a quick description of the function then hit Create new module.

PubNub Portal Functions Creation

Here you'll pick to either create a new function or to import a function from third-party service providers such as AWS, Twitter, Stripe, Mapbox, and many more.

Let's create our own function for now.

Select Create function, give it a name and select Before fire for now. There are many other functions available, so make sure to read all about functions. In the box. type the channel you're going to be running this code against, and hit Create.

In this example, we're just going to catch a message and then modify it by adding extra text to the message.

export default (request) => {
console.log(request.message.text); //This is the message being sent
var updateMessage = request.message.text + "... And a little bit more" //adding some text to the message
request.message.text = updateMessage;
console.log("message:",request.message.text); //This is the updated message
return request.ok(); // returns
};

Save your function, press Start module, then Publish button for your Test Payload. You'll see the text has been updated to include the extra string.

This simple example is just the start of what you can do with Functions. The most common use cases include:

  • Announcing to a channel when someone joins/leaves
  • Pushing notifications when an IoT device goes down
  • Sending a push notification when a user enters/leaves a geo-fenced area
  • Connecting users to chatbots
  • Collecting aggregate data from sensors for dashboard analytics
  • Triggering backups

And that's before adding functions for things like Language Translation, SMS, Profanity filtering from third-party services, or even chaining functions together!

Being able to have complete control over every action in your PubNub environment is what makes PubNub unique compared to other providers, and functions are a means to add even more distinct ways of building your applications.

Since we're on the subject of distinct ways of building applications, if you're working with mobile devices, you might be interested in setting up mobile push notifications using PubNub.

Last updated on
On this page