Track Read/Unread Messages with PubNub Functions

April 02, 2018 0 Comments

Track Read/Unread Messages with PubNub Functions

 

 

A while back, we promised we’d make it super easy method for tracking Unread Message Counts in your app. Now it is possible!

Using PubNub Functions, you can add permanent state objects and values into your multi-device applications. You’ll use our atomic methods available in PubNub Functions Key/Value Storage engine. PubNub Functions Storage Engine (kvstore) is replicated to every data center, making it fast and reliable to store/retrieve data.

You’ll only need to create one function to incrementdecrement and retrieve the current count of your unread messages.

Count Unread Messages

Our Function will count messages sent to a channel and save the value using an atomic increment and decrement methods using a key named after the channel and user ID. This is a practical design pattern called “conventional namespacing”. It means that you’ll use hints and pieces of information found in the message to create a name that is constructible based on the information in the message. We will be using the channel name in this example for our conventional name-spacing.

This first function will increment a value to track the unread messages in a user’s inbox.

Increment and Decrement the Unread Message Counter

  • Channel: room.
  • Event: On-Before Publish
// Access to Distributed Database 
const db = require('kvstore');
export default (request) => { // Conventionally build the Key ID based on the request parameters and channel name. let counterId = request.channels[0] + '/' + request.params.uuid; // Increment or Decrement the unread message counter let method = request.message.read ? -1 : 1; // Increment/Decrement and read the unread message counter return db.incrCounter( counterId, method ).then(()=>{ return db.getCounter(counterId).then((counter) => { request.message.unread = counter || 0; return request.ok(); }); });
}

Now any JSON Message published to this channel hierarchy room. will track unread messages by incrementing a counter. The counter can be decremented by including a read flag. This read method may also be used as a read-receipttracking system if desired.

You can learn more about read-receipts in Read Receipts Pattern for Realtime Chat Apps.

Using the Counter

Publish a message to room.john-smith like this:

{ "message" : "Hello John!" }

John will receive your message and an unread message counter is added to the message. The message will have been augmented with a unread variable. Now the message looks like this:

{ "message" : "Hello John!", "unread" : 1 }

John can respond with a read-receipt reply by publishing:

{ "read" : true } 

The message will update the read receipt with a unread counter.

{ "read" : true, "unread" : 0 } 

That’s it! You did it. Patterns will change based on group and one-to-one messaging apps.


Tag cloud