Stamplay + Algolia

Introduction

Stamplay algolia 1

You like building fast web & mobile application, but don’t have much time or knowledge to write the server-side application? No worries, that can be easily done using Stamplay, a powerful backend service that allows users to build full-stack applications without having to write server-side code. With Stamplay, an application’s backend solution is built through hooking up, and configuring any number components available via the Stamplay Editor. Inside the Editor one can configure a user authentication strategy; be it social or local, define user roles, data-model collections, configure Flows, 3rd Party Services Integrations, and even custom server-side Code Blocks when you need it.

By using Stamplay Flows , which are like lifecycle hooks to events within your application, we can leverage the Algolia API an allow application data to be indexed with ease without the need for any further code than what it takes to create, update and delete Stamplay data before Algolia is in the picture.

In this tutorial we will see how to create a contact web app that keeps all your data synced between your backend, on the Stamplay side, and your Algolia index. So your search engine always returns fresh content.

Prerequisites

Be familiar with Stamplay

This tutorial assumes your are familiar with Stamplay, how it works, and how to build basic Stamplay applications. If you would like to learn more before continuing on, we suggest reading the following documentation and tutorials:

Import Existing data to Algolia & re-index

If you don’t have any existing data stored on Stamplay, feel free to jump to the section Add, Update, or Delete Algolia Index Data.

To import existing data from Stamplay into Algolia programmatically we will define a Code Block that will retrieve the data from Stamplay, then batch index the records.

Add Algolia Realtime Search to Project

To start adding Algolia to your Stamplay application, first we will need your Application ID, and your Admin API Key from API-Keys tab in the Dashboard. Then inside the Stamplay Editor, add the Algolia integration through the Components page under Flows; all you need to do is enter the Application ID and Admin API Key from Algolia into the corresponding fields and submit. Keep these credentials handy for the importing and reindexing sections.

Next, inside our client-side application, we need to install the stamplay-js-sdk to add data to Stamplay, and the algoliasearch module to search through the indexed data on Algolia.

bower install stamplay-js-sdk algoliasearch

Finally, create a new Object schema inside the Stamplay Editor, contact, and give it two properties, name & phone.

Seed data, by visiting the Data section of the editor, and clicking the + symbol.

Import Existing data

Create a Code Block for Importing Existing Data

A CodeBlock is a server-side module, so instead of running install commands for the npm modules we will use, all we need to do is require them.

Create a CodeBlock in the Stamplay Editor as import_contacts that runs the following code:

var stamplay = require("stamplay");
var Stamplay = new stamplay('<Stamplay-APP-ID>', '<Stamplay-API-Key>')
var algoliasearch = require('algoliasearch');
var client = algoliasearch("YourApplicationID", "YourAPIKey");
var index = client.initIndex("contacts");
// Retrieve the contacts from Stamplay to import
Stamplay.Query("object", "contact")
  .pagination(1, 100)
  .exec(function(err, res) {
    if(err) return console.error(err);
    var items = res.data;
    var contacts = [];
    // Process each Stamplay Object, assign an ObjectID for Algolia from Stamplay Object _id
    items.forEach(function(item, idx, array) {
      contacts.push({
        objectID :  contacts[idx]._id,
        name : contacts[idx].name,
        number : contacts[idx].number
      })
    })
    // Batch index the contacts process in the contacts array
    index.addObjects(contacts, function(err, content) {
      cb(err, content);
    });
  })

Learn more about data indexing with the JS API Client

Invoking the import_contacts CodeBlock on the Client Side

Once our Code Block is defined we can define a function in our client side application to trigger the Code Block that will import the records into Algolia from Stamplay.

Inside your client-side app, create a function Import to activate the CodeBlock via the SDK :

function Import() {
  Stamplay.CodeBlock("import_contacts")
    .run({}, {}, function(err, res) {
      if(err) return console.error(err);
      console.log(res);
    })
}

Data will be retrieved from the Stamplay data, and records will be indexed on Algolia one by one. With this method, data will merely be added, so existing records are indexed inside Algolia, they will remain and be added in addition to.

To replace all indexed records, we will create a different CodeBlock to achieve this flow.

Reindex Data

To reindex data from Stamplay, we will execute a CodeBlock in which we will clear the index on Algolia using the clearIndex method, then reindex each record from Stamplay for the particular model we designate to fetch.

First we setup a code back as reindex_contacts.

Create a Code Block for ReIndexing Existing Data

module.exports = function(context, cb) {
  var Stamplay = require("stamplay");
  var Stamplay = new stamplay('<Stamplay-APP-ID>', '<Stamplay-API-Key>')
  var algoliasearch = require('algoliasearch');
  var client = algoliasearch("YourApplicationID", "YourAPIKey");
  var index = client.initIndex("contacts");
  // Clear the index's current records
  index.clearIndex(function(err, content) {
    if(err) return cb(err, content);
    // Retrieve the contacts from Stamplay to import
    stamplay.Query("object", "contact")
      .pagination(1, 100)
      .exec(function(err, res) {
      if(err) return cb(err, res);
      var items = JSON.parse(res).data;
      var contacts = [];
      // Process each Stamplay Object, assign an ObjectID for Algolia from Stamplay Object _id
      for(var i =0; i < items.length; i+= 1) {
        contacts.push({
          objectID :  items[i]._id,
          name : items[i].name,
          number : items[i].number
        });
      }
      // Batch index the contacts process in the contacts array
      index.addObjects(contacts, function(err, content) {
        cb(err, content);
      });
    });
  });

Invoking the reindex_contacts CodeBlock on the Client Side

Then inside our client side app we can add a function that will trigger the Code Block in Stamplay as defined above.

function Reindex() {
  Stamplay.CodeBlock("reindex_contacts")
    .run({}, {}, function(err, res) {
      if(err) return console.error(err);
      console.log(res);
    })
}

Add, Update, or Delete Algolia Index Data

Stamplay algolia 2

Now, we need to handle the cases where data is being added, updated or deleted. We can add Flows for each of these actions, that will perform the corresponding action to our Algolia index whenever data is added, updated or deleted from Stamplay. Inside the Stamplay editor create the followings Flows:

Create and “Add Contact Index” Flow with Stamplay

Step 1

Setup a Flow that, When An Object is Created use the Algolia integration to Add an object.

Stamplay algolia 3

Step 2

Configure the trigger to only when a contact object is created.

Stamplay algolia 4

Step 3

Select Algolia from the dropdown, and select the box labeled “Add an object”.

Stamplay algolia 5

Step 4

Connect to Algolia by entering your account credentials.

Stamplay algolia 6

Step 5

Set INDEX to push to as contacts. Be sure to create a contacts index on the Algolia platform.

Set the OBJECT ID to the trigger field of the _id of the Objects Model Data in the dropdown.

Set a JSON object as the DATA field. You can use the trigger field dropdown, or access the properties off of the variable coinstance that contains the new Object.

Stamplay algolia 7

As the final step, give your Flow a name and Save and Exit.

Create and “Update Contact Index” Flow with Stamplay

###Step 1

Setup a Flow that, When An Object is Updated use the Algolia integration to Update an object.

Stamplay algolia 8

Step 2

Configure the trigger to only when a contact object is updated.

Stamplay algolia 9

Step 3

Select Algolia from the dropdown, and select the box labeled “Update an object”.

Stamplay algolia 10

Step 4

Set INDEX to update the record matching in the contacts index.

Set the OBJECT ID to the trigger field of the _id of the Objects Model Data in the dropdown.

Set a JSON object as the DATA field. You can use the trigger field dropdown, or access the properties off of the variable coinstance that contains the new Object.

Stamplay algolia 11

As the final step, give your Flow a name and Save and Exit.

Create and “Delete Contact Index” Flow with Stamplay

Step 1

Setup a Flow that, When An Object is Deleted use the Algolia integration to Delete an object.

Stamplay algolia 12

Step 2

Configure the trigger to only when a contact object is deleted.

Stamplay algolia 13

Step 3

Select Algolia from the dropdown, and select the box labeled “Delete an object”.

Stamplay algolia 14

Step 4

Set INDEX to delete the record matching in the contacts index.

Set the OBJECT ID to the trigger field of the _id of the Objects Model Data in the dropdown.

Stamplay algolia 15

As the final step, give your Flow a name and Save and Exit.

Client Side

Now that the flows are setup to manage our algolia index, we can simply add, update, or delete Stamplay data and the corresponding action will trigger for Algolia.

function Add(data) {
  Stamplay.Object("contact")
    .save(data)
      .then(function(res) {
       console.log(res);
      }, function(err) {
        console.error(err);
      })
}
function Update(id, data) {
  Stamplay.Object("contact")
    .update(id, data)
      .then(function(res) {
       console.log(res);
      }, function(err) {
        console.error(err);
      })
}
function Delete(id) {
  Stamplay.Object("contact")
    .remove(id)
      .then(function(res) {
        console.log(res);
      }, function(err) {
        console.log(err);
      })
}