如何使用 Firebase-Cloud-Functions 更新我的 Algolia 索引

how do I Update my Algolia Index using Firebase-Cloud-Functions

我正在使用 algolia 作为我的 firebase 应用程序的全文搜索,我能够通过 firebase-cloud-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)
  })

然后更新它我尝试了这个功能

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

但它没有用,当我部署函数“属性 'id' 在类型 'Change< QueryDocumentSnapshot >' 上不存在”时出现此错误。“=12=]

该错误与 Algolia 无关。它由 TypeScript 抛出,因为您试图在 onUpdate firestore 触发器中访问 snap.id

查看 API 引用 (https://firebase.google.com/docs/reference/functions/providers_firestore.documentbuilder.html#onupdate),您可以看到传递给回调函数的第一个参数是 Change<DocumentQuerySnapshot> 类型。 Change 为其 beforeafter 属性使用通用类型(在本例中为 DocumentQuerySnapshot)。 Change 类型本身没有 属性 id.

因此尝试像这样访问它:snap.after.id.