Skip to content

Instantly share code, notes, and snippets.

@ajb413
Created March 4, 2019 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajb413/ee45d0cf1d501f498a0f483d6d11619b to your computer and use it in GitHub Desktop.
Save ajb413/ee45d0cf1d501f498a0f483d6d11619b to your computer and use it in GitHub Desktop.
PubNub v4 JS Storage & Playback sample code
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Count of Channel Messages (up to 100)
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
const getPreviousCountMessages = (count) => {
pubnub.history({
channel: 'time-publish-example-channel',
count
}, function (status, response) {
// `count` Array of previous messages is in:
// response.messages;
});
});
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Time slice of messages (up to 100 at a time)
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
const getPreviousMessagesTimeSlice = () => {
const nowJsTimestamp = new Date().getTime();
const tenMinutes = 10 * 60 * 1000;
pubnub.history({
channel: 'time-publish-example-channel',
start: nowJsTimestamp + '0000',
end: (nowJsTimestamp - tenMinutes) + '0000',
}, function (status, response) {
// Array of previous messages is in:
// response.messages;
});
});
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Time slice of messages (unlimited messages, can be dangerous for clients)
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
function messageHandler(status, response) {
const msgs = response.messages;
const start = response.startTimeToken;
const end = response.endTimeToken;
// Do something with `response.messages`
// Subsequent fetch for more historical messages
if (msgs.length === 100) {
getAllMessages(start);
}
}
function getAllMessages(nowJsTimestamp) {
if (typeof nowJsTimestamp !== 'string') {
nowJsTimestamp = new Date().getTime() + '0000';
}
pubnub.history({
channel: 'time-publish-example-channel',
start : nowJsTimestamp,
stringifiedTimeToken: true,
}, messageHandler);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment