Home > Software engineering >  how do I Update my Algolia Index using Firebase-Cloud-Functions
how do I Update my Algolia Index using Firebase-Cloud-Functions

Time:03-22

Am Using algolia as a full-text search for my firebase app and I was able to create and delete indexes via firebase-cloud-functions but to updated I've tried and did not succeed here are the functions:

//* am using Typescript
const env = functions.config()

const client = algoliasearch(env.algolia.app_id, env.algolia.admin_api_key)
const index = client.initIndex('Products')

//the function to create index
export const onProductCreated = functions.firestore
  .document('Products/{productId}')
  .onCreate((snap, ctx) => {
    return index.saveObject({
      objectID: snap.id,
      ...snap.data(),
    })
  })

//the function to delete index
export const onProductDeleted = functions.firestore
  .document('Products/{productId}')
  .onDelete((snap, ctx) => {
    return index.deleteObject(snap.id)
  })

then to update it I tried this functions

export const onProductCreated = functions.firestore
  .document('Products/{productsId}')
  .onUpdate((snap, ctx) => {
    return index.partialUpdateObject({
      objectID: snap.id,
      ...snap.data(),
    })
  })

But it didn't work, It gave an this error when I deployed the functions "Property 'id' does not exist on type 'Change< QueryDocumentSnapshot >'."

CodePudding user response:

The error is not related to Algolia. It is thrown by TypeScript because you are trying to access snap.id in the onUpdate firestore trigger.

Looking at the API reference (https://firebase.google.com/docs/reference/functions/providers_firestore.documentbuilder.html#onupdate) you can see that the first argument passed to the callback function is of type Change<DocumentQuerySnapshot>. Change uses the generic type (in this case DocumentQuerySnapshot) for its before and after properties. The Change type itself does not have a property id.

Therefore try accessing it like so: snap.after.id.

  • Related