0
votes

I've want to sync my Cloud Firestore with Algolia search index. I'm currently only able to deploy the firestore function, but it wont trigger onWrite or onChange. I'm following this guide: Angular Full Text Search With Algolia Backend

As you can see the JS is deployed but it wont trigger when i add, remove or change a document in the database. The log don't show it either.

Database design:

-|search
    -|searchId
        -|id: string
        -|name: sting
        -|ref: string

Database rule:

//Search field
match /search/{searchId}{
    allow read;
  allow write: if request.auth != null;
}

JS function:

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

const algoliasearch = require('algoliasearch');
const algolia = algoliasearch(functions.config().algolia.appid, functions.config().algolia.adminkey);


exports.updateIndex = functions.database.ref('/search/{searchId}').onWrite(event => {

  const index = algolia.initIndex('search');

  const searchId = event.params.searchId
  const data = event.data.val()

  if (!data) {
    return index.deleteObject(searchId, (err) => {
      if (err) throw err
      console.log('Search Removed from Algolia Index', searchId)
    })

  }

  data['objectID'] = searchId

  return index.saveObject(data, (err, content) => {
    if (err) throw err
    console.log('Search Updated in Algolia Index', data.objectID)
  })

});

enter image description here

1

1 Answers

0
votes

I was facing similar problem. Change those lines:

exports.updateIndex = functions.database.ref('/search/{searchId}')...
to
exports.updateIndex = functions.firestore.document('search/{searchId}')...

and
const data = event.data.val()
to
const data = event.data.exists ? event.data.data() : null;

and it should work. It worked for me but I am facing now
Function returned undefined, expected Promise or value log error and can't solve it but function works.