Save PubNub Messages to your Private Database
We wrote an article that talks about the right way to log JSON Messages to a Private Database.
While many approaches exist. One is best. Using PubNub Functions. You will asynchronously save messages reliably to your Database. Using an OnAfter Publish Event. Your database needs to be accessible via a secured HTTPS endpoint.
PubNub does not index your messages using FTS Indexing; at time of writing. You may want Full Text Search Indexing using your database or use an API provider like https://www.algolia.com/ for full text searching.
Data is valuable. AI and ML allows you to create insight from your data using Tensorflow. You may want to run data analysis for the message content. Using EMR / Hadoop or other big data analysis software.
You will use PubNub Functions to save your message asynchronously into your database system easily by following these steps.
To get started is easy. Assuming you already have a stream of messages being published to a PubNub data channel. Follow these easy steps. Successfully you will create a realtime function that is triggered every Publish event.
- Collect a list of channel(s). You may be interested in ALL channels
*
.
- In your Account Dashboard find your app, then click Functions.
- Create a new Module for your specified API key set.
- Create a new OnAfter event handler on
*
channel.
- Use the following example code to save, asynchronously, your messages to your database.
- Make sure to modify the URL/Parameters to fit your needs.
Asynchronous HTTPS Save Message Function
// Request Handler
export default request => {
return save(request).then( () => request.ok() );
}
// Async Logging/Save of JSON Messages
function save( data, retry=3 ) {
const xhr = require('xhr');
const post = { method : "POST", body : request.message };
const url = "https://my.company.com/save"; // <-- CHANGE URL HERE
// save message asynchronously
return xhr.fetch( url, post ).then( serverResponse => {
// Save Success!
}).catch( err => {
// Retry
if (retry > 0) save( data, --retry );
});
}