javascript

JavaScript Storage & Playback for Real-Time Apps | PubNub

We’ll create messages which are stored in the PubNub Real Time Network and then use the history() API call to the retrieve stored messages in various ways.

Tutorial Contents:

Getting Started

All you need to get started is a web browser that lets you interact with the JavaScript Console such as Google Chrome. In Chrome the JavaScript Console is built-in, while in other browsers this may require an additional plug-in such as FireBug for FireFox.

Step 1: Initialize the PubNub API

First off we’ll need to initialize just as we did in previous tutorials. First load the pubnub.html file by clicking here. Then open the JavaScript Console. Paste the example below into the console and hit enter to get started.

 // Initialize with Publish & Subscribe Keys
 
 var pubnub = PUBNUB.init({
     publish_key: 'demo',
     subscribe_key: 'demo',
     uuid: 'Fred_Rerun_Stubbs'
 });
  1. Open the Chrome Web Browser.

  2. Open the JavaScript Console.

  3. Open the pubnub.html file created in the previous tutorial.

  4. Paste the example code above into the JavaScript console and hit enter.

Initialize!

Storage & Playback for JavaScript Tutorial Step 1: Initialize!

Step 2: Historically Speaking

We will subscribe to out channel I’ll call history_channel

 function pub() {
    i = 0 ;
    while (i<=500)  {
       // publish 500 messages...
       pubnub.publish({
         channel: 'history_channel',
         message: "message: " + i
       });
       i++;
    };
 };

Paste the example code above into the JavaScript console and hit enter.

Adding pub() function

Storage & Playback for JavaScript Tutorial Step 2: Adding pub() function

Step 3: Auto-generate Messages

We’ll take advantage of the connect callback and specify the pub() function we created in the previous step. As soon as we are connected to the channel the callback will fire and the messages will be published.

 // publish on subscribe
 
 pubnub.subscribe({
    channel: 'history_channel',
    message: function(m){console.log(JSON.stringify(m))},
    connect: pub()
 });

Paste the example code above into the JavaScript console and hit enter.

Publishing 500 messages!

Storage & Playback for JavaScript Tutorial Step 3: Publishing 500 messages!

Step 4: Create A Message History

Now that we have some messages stored in the PubNub cloud, we’ll cover a few different ways we can recall them. First off, we will request the 100 most recently published (i.e. newest) messages. By default the history() function does exactly this.

 // publish on subscribe
 
 pubnub.history({
     channel: 'history_channel',
     callback: function(m){console.log(JSON.stringify(m))},
 });

The output of the call is sent to the callback and the resulting message contains an array of 100 messages, an end timetoken, and a start timetoken representing the temporal bounds of the messages returned.

  1. Paste the example code above into the JavaScript console and hit enter.

  2. Click on the response to inspect the array.

Returning the last 100 messages.

Storage & Playback for JavaScript Tutorial Step 4: Retrieve Last 100 Messages

Step 5: Retrieve Last 100 Messages.

Next we will request only the newest message. To do this we will use the history() function and specify a message count of 1. For the callback we will use a more structured function to grab each part of the response and print them along with some text.

 // Request Last Message.
 
 pubnub.history({
    channel: 'history_channel',
    count: 1,
    callback: function(m){console.log( "MESSAGE LIST => \r\n" + m[0] + "\r\n\r\n", "\r\nEND TOKEN => " + m[1] + "\r\n", "\r\nSTART TOKEN => " + m[2] + "\r\n") }
 });

As you can see the START TOKEN and END TOKEN returned are the same representing the time that this single message "message: 500" was published.

Retrieve newest message.

Storage & Playback for JavaScript Tutorial Step 5: Retrieve newest message

Similarly we can request the very first published (i.e. oldest) message by adding the reverse argument and setting it to true.

 pubnub.history({
    channel: 'history_channel',
    count: 1,
    reverse: true,
    callback: function(m){console.log( "MESSAGE ARRAY => \r\n" + m[0] + "\r\n\r\n", "\r\nEND TOKEN => " + m[1] + "\r\n", "\r\nSTART TOKEN => " + m[2] + "\r\n") }
 });
  1. Paste the example code above into the JavaScript console and hit enter.

Retrieve oldest message.

Storage & Playback for JavaScript Tutorial Step 5: Retrieve oldest message.

Step 6: Get messages since start time.

Now we will attempt to retrieve 50 messages starting with a specific start time. If we use the time token from the last example, we can use it as a starting point for our next message query.

 // Get messages since start time
 
 pubnub.history({
    channel: 'history_channel',
    count: 50,
    start: 13827485886365111,
    callback: function(m){console.log(JSON.stringify(m))}
 });

This history() call returns 50 messages starting with the newest message since 13827485886365111 and ending with the 50th oldest message.

Return the last 50 newest messages.

Storage & Playback for JavaScript Tutorial Step 6: Return the last 50 newest messages.

Step 7: Get messages since end time

Now we will get the most recently published messages stopping at an end timetoken. Since PubNub always starts with the most recent message of an interval by default, when we specify an end time it is a point of time in the past.

For this example we’ll generate a new time token by using the time token from the previous example and subtract 10,000,000 (1 second). For example:

 13827485886365111 - 10000000 = 13827485876365111

We’ll use our new time token 13827485876365111 and specify it with the end argument. This should give us all the messages published between now and the end time.

 pubnub.history({
    channel: 'history_channel',
    end: 13827485876365111,
    callback: function(m){console.log(JSON.stringify(m))}
 });
Getting messages since end time.

Storage & Playback for JavaScript Tutorial Step 7: Retrieve Messages Since End Timetoken

Step 8: Get messages between start and end time

We can combined what we’ve learned in the previous examples to construct a history() query that is a time slice of messages between two points in time.

In this example we’ll retrieve a 1 second window of messages ending on the previous examples timetoken stored. This token will be our new start token.

We’ll construct a new end time token by subtracting 1 second from our start token.

13827485776355504 - 10000000 = 13827475876355504
 pubnub.history({
    channel: 'history_channel',
    count: 100,
    start: 13827485876355504,
    end: 13827475876355504,
    callback: function(m){console.log(JSON.stringify(m))}
 });

There were query only 9 messages between time start time token and the end time token.

Getting a time slice of messages

Storage & Playback for JavaScript Tutorial Step 8: Message Paging

Step 9: Paging Through Messages.

Since PubNub only returns 100 messages at a time for a history call, sometimes it maybe necessary to page through a large number of messages to see the entire set of available messages. We can do this by specifying a start and end time token as before, but instead of calculating by hand (ugh!) we’ll use the time tokens bounding a response returned by the history() call to guide each query.

For example this history() call returns the most recent 10 messages and sets a variable stime to the end time token returned in the response which we will use in our next response. It also prints them out to the Console with labels so we can see what the token was.

 pubnub.history({
    channel: 'history_channel',
    count: 10,
    callback: function(a){
       stime = a[1];
       console.log("end: " + a[1], " start: " + a[2]);
       console.log(a[0]);
    }
 });
Paging back 10 messages at a time.

Storage & Playback for JavaScript Tutorial Step 9: Message Paging

Now our next query will use stime as a start time and will return up to the next 10 most recent messages:

 pubnub.history({
    channel: 'history_channel',
    count: 10,
    start: stime,
    callback: function(a){
       stime = a[1];
       console.log("end: " + a[1], " start: " + a[2]);
       console.log(a[0]);
    }
 });
Paging back 10 messages further in time.

Storage & Playback for JavaScript Tutorial Step 9: Message Paging

Additional Resources

For additional Storage & Playback resources take a look at:

  • The full PubNub API reference for JavaScript SDK: here

  • Storage & Playback overview: here

  • PubNub REST API here

Loading...