Firebase guide & Firebase Cloud Functions examples

Firebase Guide

Recently we had a few community members point out that our Firebase guide was out of date. Thank you @lsamaria and others who mentioned it.

I’ve updated the guide to use the most recent Firebase libraries, including firebase-admin for authentication. All of the example code now lives inside of a repository algolia-firebase-nodejs that you can configure and run. Tasks for an initial data import vs. live sync are split into different files.

Firebase Functions

Recently Firebase announced support for custom functions that can be run inside of their cloud.

Firebase SDK for Cloud Functions integrates the Firebase platform by letting you write code that responds to events and invokes functionality exposed by other Firebase features.

Previously, you would have to run a one-off Node.js (or other) process to do this, but no longer.

The repository functions-samples contains dozens of examples of how to use functions. One of the examples, fulltext-search, is based on Algolia and shows how you can use functions to search and index Firebase data.

Here’s the part that does indexing, in an impressively small function:

// Updates the search index when new blog entries are created or updated.
exports.indexentry = functions.database.ref('/blog-posts/{blogid}').onWrite(event => {
  // TODO: Make sure you configure the `algolia.key` and `algolia.secret` Google Cloud environment variables.
  const client = algoliasearch(functions.config().algolia.key, functions.config().algolia.secret);
  const index = client.initIndex('users');

  const firebaseObject = event.data.val();
  firebaseObject.objectID = event.data.key;

  return index.saveObject(firebaseObject).then(
      () => admin.database().ref(event.timestamp));
});
2 Likes

@dzello Hello friend! I’ve been working on other part of my apps (I’m a solo dev :() and I’m finally getting back to Alogolia today. I just saw the update you mentioned. I’m about to start the Alogolia/iOS merge right now and see how it works not including the initIndex and just using the reindexIndex. I noticed that you now have:

> // Updates the search index when new blog entries are created or updated.
> exports.indexentry = functions.database.ref('/blog-posts/{blogid}').onWrite(event => {
>   // TODO: Make sure you configure the `algolia.key` and `algolia.secret` Google Cloud environment variables.
>   const client = algoliasearch(functions.config().algolia.key, functions.config().algolia.secret);
>   const index = client.initIndex('users');

>   const firebaseObject = event.data.val();
>   firebaseObject.objectID = event.data.key;

>   return index.saveObject(firebaseObject).then(
>       () => admin.database().ref(event.timestamp));
> });

Does this replace all of the node.js code that I originally had inside my app.js file (I didn’t use the initial index like you suggested)?

> //Firebase Initialization
> var admin = require("firebase-admin");
> admin.initializeApp({
>   credential: admin.credential.cert({
>     projectId: "...",
>     clientEmail: "...",
>     privateKey: ..."
>   }),
>   databaseURL: ..."
> });

>   var firebase = require('firebase');
>   var config = {
>       apiKey: "myFirebaseAPIKey",
>       authDomain: "myFirbaseProjectID.firebaseapp.com",
>       databaseURL: "myFB_URL",
>       storageBucket: "myFirebaseStorageBucket"
>     };
>     firebase.initializeApp(config);

>   //Algolia Initialization
>   var algoliasearch = require('algoliasearch');
>   var client = algoliasearch('myAlgoliaApplicationID', 'myAlgoliaPrivateAPIKey');
>   var index = client.initIndex('meal');
>   var rootRef = firebase.database().ref('meal');

>   **//Reindex Data**
>   // Get all data from Firebase
>   rootRef.on('value', reindexIndex);
>   function reindexIndex(dataSnapshot) {
>     // Array of objects to index
>     var objectsToIndex = [];
>       // Create a temp index
>       var tempIndexName = 'meal_temp';
>       var tempIndex = client.initIndex(tempIndexName);
>       // Get all objects
>       var values = dataSnapshot.val();
>       // Process each Firebase object
>       for (var key in values) {
>         if (values.hasOwnProperty(key)) {
>           // Get current Firebase object
>           var firebaseObject = values[key];
>           // Specify Algolia's objectID using the Firebase object key
>           firebaseObject.objectID = key;
>           // Add object for indexing
>           objectsToIndex.push(firebaseObject);
>         }
>       }
>       // Add or update new objects
>       index.saveObjects(objectsToIndex, function(err, content) {
>         if (err) {
>           throw err;
>         }
>         // Overwrite main index with temp index
>         client.moveIndex(tempIndexName, 'meal', function(err, content) {
>           if (err) {
>             throw err;
>           }
>           console.log('Firebase<>Algolia reimport done');
>         });
>       });
>     }

>   **//Add or Update Data**
>   // Listen for changes to Firebase data
>   rootRef.on('child_added', addOrUpdateObject);
>   rootRef.on('child_changed', addOrUpdateObject);
>   function addOrUpdateObject(dataSnapshot) {
>     // Get Firebase object
>     var firebaseObject = dataSnapshot.val();
>     // Specify Algolia's objectID using the Firebase object key
>     firebaseObject.objectID = dataSnapshot.key;
>     // Add or update object
>     index.saveObject(firebaseObject, function(err, content) {
>       if (err) {
>         throw err;
>       }
>       console.log('Firebase<>Algolia object saved');
>     });
>   }

>   **//Delete Data**
>   // Listen for changes to Firebase data
>   rootRef.on('child_removed', removeIndex);
>   function removeIndex(dataSnapshot) {
>     // Get Algolia's objectID from the Firebase object key
>     var objectID = dataSnapshot.key();
>     // Remove the object from Algolia
>     index.deleteObject(objectID, function(err, content) {
>       if (err) {
>         throw err;
>       }
>       console.log('Firebase<>Algolia object deleted');
>     });
>   }

Hi @LanceSamaria!

That first code example is from the firebase-functions project - that is a slightly different way to integrate Firebase and Algolia and you don’t want to mix the two.

Where you should look to compare with what you have now is this repository: algolia-firebase-nodejs.

1 Like

@dzello Good morning. Man this is a lot of work :blush::blush:. I’m going to try to use the version you suggested between today and tomorrow. I’ll send you an update by the weekend. Hopefully it’s a smooth transition.

But since the older code was valid, shouldn’t it still work correctly? What are the benefits of updating to the new firebase-functions codes? What are the cons of keeping the older code?

Thanks for the name change!!

Lance

1 Like