Need help syncing Algolia with Firebase RealTimeDatabase for an iOS app via a Cloud Function

I’ve been using Heroku to sync Algolia with the Firebase RealTimeDatabase. I’ve recently started using Cloud Functions and I’ve decided to abandon Heroku in favor of that. I’m a native Swift iOS dev so Node.js is still foreign to me. After I’ve initialized my Firebase project with Cloud Functions I’ve been looking at tutorials on how to sync Algolia with the RDB but mostly everything is to sync with FireStore which I don’t use.

I have 2 questions:

For other uses the way I had to sync Cloud Functions with my iOS app, inside the view controller that connects with the cloud function, I had do this (it all works fine):

import Firebase
lazy var functions = Functions.functions()

@IBAction func buttonTapped(_ sender: UIButton) {

    let data: [String: Any] = ["postId": "abc123", "uid": Auth.auth().currentUser!.uid, "name": "Adidas"]

    let cloudFunctionName = "getData"

    functions.httpsCallable(cloudFunctionName).call(data) { (result, error) in
        // ...
    }
}

And the cloud function:

exports.getData = functions.https.onCall((data, context) => {
    // ...
});

1- Do I need to do something similar, specifically add lazy var functions = Functions.functions() to the view controller with my search controller to connect my iOS app with the cloud function that I’m going to use for Algolia? Fyi I already have all of the previous Algolia code in the vc from using Heroku.

2- I’ve ran all the npm code needed for the cloud function Algolia and Firebase libraries, and config variables/API keys. Following this Algolia tutorial, is this all I need to sync? The tutorial makes this very easy but I want to make sure. This is the exact file that I am currently using.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

const algoliasearch = require('algoliasearch');
const client = algoliasearch(functions.config().algolia.app, functions.config().algolia.key);
const index = client.initIndex(functions.config().algolia.index);

const sneakersRef = admin.database().ref('/sneakers');
sneakersRef.on('child_added', addOrUpdateIndexRecord);
sneakersRef.on('child_changed', addOrUpdateIndexRecord);
sneakersRef.on('child_removed', deleteIndexRecord);

function addOrUpdateIndexRecord(post) {
  
  const record = post.val();
  
  record.objectID = post.key;
  
  index
    .saveObject(record)
    .then(() => {
      console.log('Firebase object indexed in Algolia', record.objectID);
    })
    .catch(error => {
      console.error('Error when indexing post into Algolia', error);
      process.exit(1);
    });
}

function deleteIndexRecord({key}) {
  
  const objectID = key;
  
  index
    .deleteObject(objectID)
    .then(() => {
      console.log('Firebase object deleted from Algolia', objectID);
    })
    .catch(error => {
      console.error('Error when deleting contact from Algolia', error);
      process.exit(1);
    });
}

exports.getData = functions.https.onCall((data, context) => {
    // ...
});

exports.helloWorld = functions.https.onRequest((request, response) => {
    // ...
)};

I guess because I’m not well enough acquainted with Node.js but after I deploy I would expect to see a response like:

**✔** **functions[helloWorld(us-location)]:** Successful update operation.

**✔** **functions[getData(us-location)]:** Successful update operation.

**✔** **Deploy complete!**

It said nothing about the addOrUpdateIndexRecord() or deleteIndexRecord() functions.

Hi @flowtinc !

I’m sorry but I feel like your question is not related to Algolia per se. The tutorial indeed is quite straightforward and should help you get where you want to go but how to use it with Cloud Functions is another subject.
Someone might be of better help however so I hope you’ll get your answer soon! Cheers

@chloe.liban hey thanks for the reply, it’s all good, I’ll figure it out. Cheers!!! :slight_smile:

Good luck :blush: and don’t hesitate to post your solution here when you’ll find it, I’ll be interested to know how to do it! Have a good day

cool, I got you. I’m going to work on it tomorrow and should have an answer by then.

@ chloe.liban Sorry for the wait, I’ve been busy working on another project and just got back to this today.

The code in my question with sneakers.on from the Algolia tutorial didn’t work, it returned an error. I had to use this code instead which 100% works fine for all CRUD operations. I also did not have to do anything inside my iOS app to trigger the code to run.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

const algoliasearch = require('algoliasearch');
const client = algoliasearch(functions.config().algolia.app, functions.config().algolia.key);
const index = client.initIndex(functions.config().algolia.index);

exports.updateRecord = functions.database.ref('/sneakers/{postId}').onWrite((change,context) => {

    const postId = context.params.postId;
    const data = change.after.val();

    if (!data) {
        return index.deleteObject(postId, (err) => {
            if (err) throw err
        console.log('PostId Removed from Algolia Index', postId) // this actually doesn't print but irregardless the code works
    })}

    data['objectID'] = postId

    return index.saveObject(data, (err, content) => {
        if (err) throw err
        console.log('PostId Updated in Algolia Index', data.objectID) // this actually doesn't print but irregardless the code works
    });
});

To get the above code to work I had to follow this youtube then add this change and this change and do a little reading using this.