首页 > 解决方案 > Firebase functions algolia onWrite

问题描述

I want the user I added for firebase to be automatically added to the algolia, and I created such a function, but I get some errors

My onWrite Functions

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

I am receiving such an error

 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)

Actually I don't understand database.ref('/Users/{userId}')? How can I do?

标签: javascriptfirebasefirebase-realtime-databasegoogle-cloud-functionsalgolia

解决方案


Change this:

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

into this:

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

The cloud functions were updated and onWrite now has two parameters change and context. To be able to retrieve the wildcards then you need to use the context parameter.

The context parameter provides information about the function's execution. Identical across asynchronous functions types, context contains the fields eventId, timestamp, eventType, resource, and params.

more info here:

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


推荐阅读