Firebase函数-ReferenceError:未定义事件

时间:2018-11-24 11:25:03

标签: android node.js firebase firebase-realtime-database google-cloud-functions

我正在尝试做一个简单的通知功能 但是每次我触发该函数时,都会出现错误

  

TypeError:无法读取未定义的属性“ params”       在export.sendNotification.functions.database.ref.onWrite(/user_code/index.js:23:32)       在cloudFunctionNewSignature(/user_code/node_modules/firebase-functions/lib/cloud-functions.js:105:23)       在cloudFunction(/user_code/node_modules/firebase-functions/lib/cloud-functions.js:135:20)       在/var/tmp/worker/worker.js:758:24       在process._tickDomainCallback(internal / process / next_tick.js:135:7)

或者我得到错误

  

TypeError:无法读取未定义的属性“ user_id”

我从here那里得到了答案

但是我一点也没有帮助,我也找不到问题。这是我的代码

'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change,context) => {

const user_id = event.params.user_id;
const notification_id = event.params.notification_id;

console.log('We have a notification from : ', user_id);

if(!context.data.val()){

return console.log('A Notification has been deleted from the database : ', 
notification_id);

}

const fromUser =admin.database().ref(`/notifications/${user_id}/${notification_id}`).once('value');

return fromUser.then(fromUserResult => {

const from_user_id = fromUserResult.val().from;

console.log('You have new notification from  : ', from_user_id);

const userQuery = admin.database().ref(`Users/${from_user_id}/name`).once('value');
const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');

return Promise.all([userQuery, deviceToken]).then(result => {

  const userName = result[0].val();
  const token_id = result[1].val();

  const payload = {
    notification: {
      title : "New Friend Request",
      body: `${userName} has sent you request`,
      icon: "default",
      click_action : "none"
    },
    data : {
      from_user_id : from_user_id
    }
  };

  return admin.messaging().sendToDevice(token_id, payload).then(response => {

    return console.log('This was the notification Feature');

     });

   });

  });

});

1 个答案:

答案 0 :(得分:2)

您从未定义event,因此未定义。您正在尝试访问未定义变量的属性。您是说context.params.user_id吗?

(您可能正在使用一个过时的教程。我在Stack Overflow上经常看到这样的错误的“ sendNotification”功能。让作者知道。)