Architecture & DesignA Guide to PubNub Functions

A Guide to PubNub Functions

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

The incredible speeds attained by today’s modern Internet connections have facilitated the proliferation of real-time applications. These are applications that function within a time frame that is fast enough that the user senses their responses as being immediate for all practical purposes. Hence, the latency must be within seconds or even fractions of a second.

Up until recently, developing realtime apps has been kind of a pain and required a big engineering effort. That’s because, to build any kind of realtime functionality, you need to establish a bi-directional connection between client and server to send messages over. PubNub provides realtime APIs and global messaging infrastructure to simplify the coding your realtime apps. It utilizes a Publish/Subscribe model for realtime data streaming and device signaling which lets you establish and maintain persistent socket connections to any device and push data to global audiences in less than a quarter of a second. You can publish messages to any given channel, and subscribing clients only receive messages associated with that channel. The message payload can contain any JSON data types including numbers, strings, arrays, and objects.

In today’s article, we’ll build and test a greeting function by using the PubNub console.

Walkthrough

PubNub has online consoles for developing and managing every component of your projects and modules from API keys to debug settings. Therefore, everything that we will do today will take place on the PubNub site.

  1. Let’s start by creating an account. If you already have a Google account, you can use it to furnish your credentials.
  2. At the admin console, you’ll see a Demo Project has already been created for you. Click it to open the project in the console.
  3. There, you’ll see your Demo Keyset. Now, click on it to access its details.
  4. Under Application Add-ons at the bottom of the screen, you’ll see a number of options. Enable PubNub Functions, as shown in Figure 1:

    Enabling PubNub functions
    Figure 1: Enabling PubNub Functions

  5. The Save button will appear in the lower-left corner of the screen. Click it to save your changes.
  6. Now, we’ll create an App Module. On the left-hand menu, click PubNub Functions to bring up the PubNub Functions screen (see Figure 2):

    The PubNub Functions screen
    Figure 2: The PubNub Functions screen

  7. In the Create New Module dialog, enter “Greeting” in the ‘Enter a New App Name’ field. Click the ‘Create New Module’ button, as you can see in Figure 3:

    Creating a new module
    Figure 3: Creating a new module

    You should receive a “New Module Successfully Created” notification at the top of the page.

  8. Next, we’ll code the Function. Within the context of a realtime app, the Function is where we place the logic that runs against the message. Click the ‘+ CREATE’ button to create a new Function.
  9. In the New Function dialog, enter “Display Greeting” for the ‘Function name’, choose “Before Publish or Fire” for the ‘Function type’, and enter “display_greeting” for the ‘Channel name’ (see Figure 4):

    Completing the create sequence
    Figure 4: Completing the create sequence

  10. Click ‘Create’.

The Display Greeting Module editor will appear. It will show the Display Greeting Function in the editor with a basic skeleton. Right now, all it does is log the request and return the request as a promise resolution:

export default (request) => { 
   const kvstore = require('kvstore');
   const xhr = require('xhr');

   // Log the request envelope passed
   console.log('request', request);
   // Return a promise when you're done
   return request.ok();
}

In the preceding code:

  • The request parameter holds the PubNub message envelope object.
  • The body of the Function imports a few libraries, logs the request, and returns the request as a promise resolution. (Returning request.ok() is the equivalent to returning Promise.resolve(request)).

This Function will run each time the message enters the PubNub Data Stream Network, but before it’s further replicated and distributed to subscribers, because its type is ‘Before Publish’.

Now, we’ll modify the function code to append a name to the default “Hello” message.

  1. In the function code editor, replace the console.log line with the following:
    request.message.greeting += " world!";
  2. Click ‘Save’.
  3. Now, let’s test our function. In the ‘Test Payload’ field, enter the following JSON literal, as shown in Figure 5:
    {
       "greeting": "Hello"
    }
    

    Displaying the message information
    Figure 5: Displaying the message information

  4. Click ‘Save Test’.
  5. Click ‘Publish’ to send the message to the ‘hello_greeting’ channel. Output will be printed to the test console:
    11:34:36  block: Deploying in regions: Eastern US,
       Western US, Asia, Central Europe.
    11:34:38  block: Module is now globally deployed. 
    11:34:41 publish: { "greeting": "Hello world!" }
    

As you can see, the greeting now says “Hello world!”.

Using the Production Developer Console

You can see from the preceding examples that the built-in test console is convenient, but sometimes, you may want to use the production developer console instead to better emulate a production environment. To use the production developer console:

  1. Navigate to the PubNub Developer Console.
  2. Set the ‘channel’ to “hello_greeting”.
  3. Set the publish and subscribe keys to those of the Demo Keyset.
  4. Click ‘Subscribe’.
  5. Clicking the Publish button this time displays the same production output that your client would see the contents shown in Figures 6 and 7:

    Publishing the greeting
    Figure 6: Publishing the greeting

    Production messages
    Figure 7: Production messages

Conclusion

There’s a lot more to PubNub than Functions. It also offers a ChatEngine, Data Stream Network, Realtime Messaging, and many other tools aimed at realtime development. Its services are not completely free, but are probably well worth the cost for most businesses.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories