Angular2Angular2 Storage & Playback API Reference for Realtime Apps

PubNub's Storage & Playback feature enables developers to store messages as they are published, and retrieve them at a later time. Our storage layer is a time-series based database. Each published message is timestamped to the nearest 10 nanoseconds.

Learn more about our Storage & Playback feature here.


Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
This function fetches historical messages of a channel.
PubNub Storage/Playback Service provides real-time access to an unlimited history for all messages published to PubNub. Stored messages are replicated across multiple availability zones in several geographical data center locations. Stored messages can be encrypted with AES-256 message encryption ensuring that they are not readable while stored on PubNub's network.
It is possible to control how messages are returned and in what order, for example you can:
  • Search for messages starting on the newest end of the timeline (default behavior - reverse = false)
  • Search for messages from the oldest end of the timeline by setting reverse to true.
  • Page through results by providing a start OR end time token.
  • Retrieve a slice of the time line by providing both a start AND end time token.
  • Limit the number of messages to a specific quantity using the count parameter.
 
Start & End parameter usage clarity:
If only the start parameter is specified (without end), you will receive messages that are older than and up to that start timetoken value.
If only the end parameter is specified (without start) you will receive messages that match that end timetoken value and newer.
Specifying values for both start and end parameters will return messages between those timetoken values (inclusive on the end value).
Keep in mind that you will still receive a maximum of 100 messages even if there are more messages that meet the timetoken values. Iterative calls to history adjusting the start timetoken is necessary to page through the full set of results if more than 100 messages meet the timetoken values.
To run History you can use the following method(s) in the Angular2 V4 SDK
  1. ParameterTypeRequiredDefaultsDescription
    Operation ArgumentsHashYesA hash of arguments.
    channel StringYesSpecifies channel to return history messages from.
    reverse Boolean Optionalfalse

    Setting to true will traverse the time line in reverse starting with the oldest message first.


    If both start and end arguments are provided, reverse is ignored and messages are returned starting with the newest message.

    count Number Optional100Specifies the number of historical messages to return.

    Default/Maximum is 100.
    stringifiedTimeToken Boolean OptionalfalseIf stringifiedTimeToken is specified as true, the SDK will return timetoken values as a strings instead of integers. Usage of setting is encouraged in javascript environments which perform round-up/down on large integers.
    start String OptionalTime token delimiting the start of time slice (exclusive) to pull messages from.
    end String OptionalTime token delimiting the end of time slice (inclusive) to pull messages from.
    callbackFunctionOptionalExecutes on a successful/unsuccessful history.
  2. ParameterTypeRequiredDescription
    Operation ArgumentsHashYesA hash of arguments.
    includeMetaBooleanOptionalWhether message meta information should be fetchded or not.
    callbackFunctionOptionalExecutes on a successful/unsuccessful history.
Retrieve the last 100 messages on a channel:
pubnub.history(
    {
        channel: 'my_channel',
        count: 100, // 100 is the default
        stringifiedTimeToken: true // false is the default
    },
function (status, response) 
    {
        console.log(response);
    }
);
// Example of Status
{
    error: false,
    operation: "PNHistoryOperation",
    statusCode: 200
}

// Example of Response
{
    endTimeToken: "14867650866860159",
    messages: [
        {
            timetoken: "14867650866860159",
            entry: "[User 636] hello World"
        },
        {...},
        {...},
        {...}
    ],
    startTimeToken: "14867650866860159"
}
  1. // get last 3 messages published to my_channel
    pubnub.history(
        {
            channel: ['my_channel'],
            reverse: true, // Setting to true will traverse the time line in reverse starting with the oldest message first.
            count: 3,
            stringifiedTimeToken: true // false is the default
        },
        function (status, response) {
            // handle status, response
        }
    );
  2. // get messages starting at timetoken order oldest first
    pubnub.history(
        {
            channel: 'my_channel',
            reverse: true, // Setting to true will traverse the time line in reverse starting with the oldest message first.
            stringifiedTimeToken: true, // false is the default
            start: '13406746780720711'
        },
        function (status, response) {
            // handle status, response
        }
    );
  3. // return 100 messages ending on timetoken
    pubnub.history(
        {
            channel: 'my_channel',
            stringifiedTimeToken: true,
            end: '13406746780720711'
        },
        function (status, response) {
            // handle status, response
        }
    )
  4.  
    Usage!
    You can call the method by passing 0 or a valid time token as the argument.
    getAllMessages = function(timetoken) {
        pubnub.history(
            {
                channel: 'history_test',
                stringifiedTimeToken: true, // false is the default
                start: timetoken
            },
            function (status, response) {
                var msgs = response.messages;
                var start = response.startTimeToken;
                var end = response.endTimeToken;
                // if msgs were retrieved, do something useful with them
                if (msgs !== "undefined" && msgs.length > 0) {
                    console.log(msgs.length);
                    console.log("start : " + start);
                    console.log("end : " + end);
                }
                // if 100 msgs were retrieved, there might be more; call history again
                if (msgs.length == 100) {
                    getAllMessages(start);
                }
            }
        );
    }
      
    //Usage examples:
    //getAllMessages();
    //getAllMessages(null);
    //getAllMessages(14264873967138188);
     
  5. pubnub.history({
        channel: 'my_channel',
        reverse: false, // false is the default
        count: 100, // 100 is the default
        stringifiedTimeToken: true // false is the default
    }).then((response) => {
        console.log(response);
    }).catch((error) => {
        console.log(error);
    });
  6. // get last 3 messages published to my_channel
    pubnub.history({
        channel: ['my_channel'],
        reverse: true, // Setting to true will traverse the time line in reverse starting with the oldest message first.
        count: 3,
        stringifiedTimeToken: true // false is the default
    }).then((response) => {
        console.log(response);
    }).catch((error) => {
        console.log(error);
    });
  7. pubnub.history({
        channel: 'my_channel',
        reverse: true, // Setting to true will traverse the time line in reverse starting with the oldest message first.
        stringifiedTimeToken: true, // false is the default
        start: '13406746780720711' // start time token to fetch
    }).then((response) => { 
        console.log(response) 
    }).catch((error) => { 
        console.log(error) 
    });
  8. pubnub.history({
        channel: 'my_channel',
        stringifiedTimeToken: true, // false is the default
        end: '13406746780720711' // start time token to fetch
    }).then((response) => { 
        console.log(response) 
    }).catch((error) => { 
        console.log(error) 
    });
  9. function getAllMessages(timetoken) {
    	pubnub.history(
    		{
    			channel: 'history_test',
    			stringifiedTimeToken: true, // false is the default
    			start: timetoken // start time token to fetch
    		}).then((response) => {
    			var msgs = response.messages;
    			var start = response.startTimeToken;
    			var end = response.endTimeToken;
    
    			// if msgs were retrieved, do something useful with them
    			if (msgs !== undefined && msgs.length > 0) {
    				console.log(msgs.length);
    				console.log("start : " + start);
    				console.log("end : " + end);
    			}
    
    			// if 100 msgs were retrieved, there might be more; call history again
    			if (msgs.length == 100) {
    				getAllMessages(start);
    			}
    		}).catch((error) => {
    			console.log(error);
    		});
    }
    
    //Usage examples:
    //getAllMessages();
    //getAllMessages(null);
  10. pubnub.history(
        {
            channel: 'my_channel',
            stringifiedTimeToken: true,
            includeMeta: true,
        },
        function (status, response) {
            // handle status, response
        }
    );

Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
This function fetches historical messages of a channel.
PubNub Storage/Playback Service provides real-time access to an unlimited history for all messages published to PubNub. Stored messages are replicated across multiple availability zones in several geographical data center locations. Stored messages can be encrypted with AES-256 message encryption ensuring that they are not readable while stored on PubNub's network.
It is possible to control how messages are returned and in what order, for example you can:
  • Page through results by providing a start OR end time token.
  • Retrieve a slice of the time line by providing both a start AND end time token.
  • Limit the number of messages to a specific quantity using the count parameter.
Start & End parameter usage clarity:
If only the start parameter is specified (without end), you will receive messages that are older than and up to that start timetoken value.
If only the end parameter is specified (without start) you will receive messages that match that end timetoken value and newer.
Specifying values for both start and end parameters will return messages between those timetoken values (inclusive on the end value).
Keep in mind that you will still receive a maximum of 25 messages per channel even if there are more messages that meet the timetoken values.
To run Batch History you can use the following method(s) in the Angular2 V4 SDK
  1. ParameterTypeRequiredDefaultsDescription
    Operation ArgumentsHashYesA hash of arguments.
    channels ArrayYesSpecifies channels to return history messages from.
    count Number Optional25Specifies the number of historical messages to return per channel.

    Default/Maximum is 25 per channel.
    stringifiedTimeTokenBooleanOptionalfalseIf stringifiedTimeToken is specified as true, the SDK will return timetoken values as a strings instead of integers. Usage of setting is encouraged in javascript environments which perform round-up/down on large integers.
    start String OptionalTime token delimiting the start of time slice (exclusive) to pull messages from.
    end String OptionalTime token delimiting the end of time slice (inclusive) to pull messages from.
    withMessageActions Boolean OptionalfalseThe flag denoting to retrieve history messages with message actions. If true, the method is limited to one channel only.
    callbackFunctionOptionalExecutes on a successful/unsuccessful fetchMessages.
  2. ParameterTypeRequiredDescription
    Operation ArgumentsHashYesA hash of arguments.
    includeMetaBooleanOptionalWhether message meta information should be fetchded or not.
    includeMessageActionsBooleanOptionalWhether message added message actions should be fetched or not.

    Throws an exception in case if API called with more than one channel.
    callbackFunctionOptionalExecutes on a successful/unsuccessful fetchMessages.
Retrieve the last 25 messages on a channel:
// assuming pubnub is an initialized instance
// start, end, count are optional
pubnub.fetchMessages(
    { 
        channels: ['ch1', 'ch2', 'ch3'], 
        start: "15343325214676133",
        end: "15343325004275466",
        count: 25 
    }, 
    (status, response) => {
        // handle response
    }
);
 
The batch history is limited to 500 channels and only the last 25 messages per channel.
//Example of status
{
    error: false,
    operation: 'PNFetchMessagesOperation',
    statusCode: 200
}

//Example of response
{ 
    channels:
    {
        "my-channel":[{
            "message":"message_1",
            "timetoken":"15483367794816642"
          },
          {
            "message":"message_2",
            "timetoken":"15483367810978163"
          },
          {
            "message":"message_3",
            "timetoken":"15483367819545303"
          },
          {
            "message":"message_4",
            "timetoken":"15483367827886667"
          }]
        "my-channel-2":[{
            "message":"message_1",
            "timetoken":"15483367827886667"
          },
          {
            "message":"message_2",
            "timetoken":"15483367819545303"
          },
          {
            "message":"message_3",
            "timetoken":"15483367810978163"
          },
          {
            "message":"message_4",
            "timetoken":"15483367794816642"
          }]
        "my-channel-3":[{
            "message":"message_1",
            "timetoken":"15483373338046565"
          },
          {
            "message":"message_2",
            "timetoken":"15483373303521793"
          },
          {
            "message":"message_3",
            "timetoken":"15483373407379141"
          },
          {
            "message":"message_4",
            "timetoken":"15483373366944653"
          }]
     }
}
  1. Fetch messages with metadata and actions

    pubnub.fetchMessages(
        {
            channels: ['my_channel'],
            stringifiedTimeToken: true,
            includeMeta: true,
            includeMessageActions: true,
        },
        function (status, response) {
            // handle status, response
        }
    );

    Fetch messages with metadata and actions Response

    // Example of status
    {
        "error": false,
        "operation": "PNFetchMessagesOperation",
        "statusCode": 200
    }
    
    // Example of response
    {
        "channels": {
            "my-channel": [
                {
                    "message": "message_1",
                    "timetoken": "15483367794816642",
                    "actions": {
                        "receipt": {
                            "read": [
                                {
                                    "uuid": "user-7",
                                    "actionTimetoken": "15610547826970044"
                                }
                            ]
                        }
                    }
                },
                {
                    "message": "message_2",
                    "timetoken": "15483367810978163"
                },
                {
                    "message": "message_3",
                    "timetoken": "15483367819545303",
                    "meta": {
                        "type": "personal"
                    }
                },
                {
                    "message":"message_4",
                    "timetoken":"15483367827886667"
                }
            ]
        }
    }

Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
Removes the messages from the history of a specific channel.
 
There is a setting to accept delete from history requests for a key, which you must enable by checking the Enable Delete-From-History checkbox in the key settings for your key in the Administration Portal.

Requires Initialization with secret key.

To Delete Messages from History you can use the following method(s) in the Angular2 V4 SDK.
  1. ParameterTypeRequiredDescription
    Operation ArgumentsHashYesA hash of arguments.
    channelStringYesSpecifies channel messages to be deleted from history.
    startStringOptionalTime token delimiting the start of time slice (inclusive) to delete messages from.
    endStringOptionalTime token delimiting the end of time slice (exclusive) to delete messages from.
    callbackFunctionOptionalIs called on successful or unsuccessful execution of deleteMessages.
pubnub.deleteMessages(
    {
        channel: 'ch1',
        start: '15088506076921021',
        end: '15088532035597390'
    },
    (result) => {
        console.log(result);
    }
);
{
    error: false,
    operation: 'PNDeleteMessagesOperation',
    statusCode: 200
}

  1. To delete a specific message, pass the publish timetoken (received from a successful publish) in the End parameter and timetoken +/- 1 in the Start parameter. e.g. if 15526611838554310 is the publish timetoken, pass 15526611838554309 in Start and 15526611838554310 in End parameters respectively as shown in the following code snippet.
    pubnub.deleteMessages(
        {
            channel: 'ch1',
            start: '15526611838554309',
            end: '15526611838554310'
        },
        (result) => {
            console.log(result);
        }
    );