External storage

Full-text search, data analytics, and audit trails are only three of many reasons you may want to store messages externally. Using PubNub Functions, you can save JSON messages to your database, asynchronously and reliably.

Assuming you already have a stream of JSON messages being published to a PubNub channel (such as chat messages or Bitcoin prices), follow these easy steps to create an asynchronous function that's triggered after every message is published.

Set up the Function

Set up a PubNub Function to get your code running on the network. This is where the calls to your database will happen.

To add the PubNub Function to an existing PubNub app, do the following:

  1. Go to the application instance on your Admin Portal.

  2. Create a new module, and then create a new After Publish or Fire Function. Configure the function to trigger on specific channels, or use * to run it on all channels.

  3. Use the following sample Function code to (asynchronously) save your JSON messages to your database. (You'll need to modify url and post to fit your needs.)

    export default request => {
    const xhr = require('xhr');
    const post = { method : "POST", body : request.message };
    const url = "https://my.company.com/save";
    // save message asynchronously
    return xhr.fetch( url, post ).then( serverResponse => {
    // Save Success!
    return request.ok();
    }).catch( err => {
    // Save Failed! handle err
    return request.abort();
    });
    }
  4. Click Start module to start the function, and test it using the Test Payload field and Publish button on the left.

For a more detailed overview of creating functions, refer to Create a Function.

Last updated on