Firebase功能algolia onWrite

时间:2018-05-18 11:36:40

标签: firebase firebase-realtime-database google-cloud-functions algolia

我希望我为firebase添加的用户自动添加到algolia,我创建了这样一个函数,但是我遇到了一些错误

我的onWrite功能

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

        var client = algoliasearch(ALGOLIA_APP_ID,ALGOLIA_ADMIN_KEY);
        const index = client.initIndex('Users');

        const userId = event.params.userId;
        const data = event.data.val()

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

        data['objectID'] = userId

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

And my Database

我收到这样的错误

 TypeError: Cannot read property 'userId' of undefined
        at exports.updateIndex.functions.database.ref.onWrite.event (/user_code/index.js:43:29)
        at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
        at next (native)
        at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
        at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
        at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
        at /var/tmp/worker/worker.js:716:24
        at process._tickDomainCallback (internal/process/next_tick.js:135:7)

其实我不懂database.ref(' / Users / {userId}')? 我该怎么办?

1 个答案:

答案 0 :(得分:2)

改变这个:

exports.updateIndex = functions.database.ref('/Users/{userId}').onWrite(event => {
  const userId = event.params.userId;
  const data = event.data.val()

进入这个:

exports.updateIndex = functions.database.ref('/Users/{userId}').onWrite((change,context) => {
  const userId = context.params.userId;
  const data = change.after.val();

云功能已更新,onWrite现在有两个参数changecontext。为了能够检索通配符,您需要使用context参数。

  

context参数提供有关函数执行的信息。跨异步函数类型相同,上下文包含字段eventIdtimestampeventTyperesourceparams

更多信息:

https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database