开发者问题收集

Android - Firebase 推送通知后端显示错误

2018-09-07
209

我没有更多的 Android 经验,几乎不懂 javascript 编码,我按照教程创建了一个 firebase 函数,现在 firebase 函数将 beta 更改为稳定版 ,我的代码显示错误:

这是我的代码 --->

'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 = context.params.user_id;
  const notification_id = context.params.notification_id;

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

  if (!event.data.exists()) {

    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 : "in.tvac.akshaye.lapitchat_TARGET_NOTIFICATION"
        },
        data : {
          from_user_id : from_user_id
        }
      };

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

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

这是我的数据库 ---->

  • 通知
  • BOhvOUJG8sWgIyTD7JLuSOgfv9v1
    • aqTdCWJYfvQiw188MqldsDtlLFf2 -LLO14ghpMruZtqwK7CR 来自:“rrajSiL7SFd7WQydkA7jwxi26s63” 类型: “请求” -LLOQ2WsWHymJvdOxrx5 来自:“rrajSiL7SFd7WQydkA7jwxi26s63” 类型:“请求” -LLfVM43o8Rt-1A55r28 -LLfxudlktvk3ysxvype

我收到此错误 --->

ReferenceError: event is not defined
    at exports.sendNotification.functions.database.ref.onWrite (/user_code/index.js:15:7)
    at cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:105:23)
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:135:20)
    at /var/tmp/worker/worker.js:733:24
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)
2个回答

在此处输入图片描述

请检查您是否已定义该事件

Sana
2018-09-08

我的问题现在已经解决,这只是因为 firebase 函数从测试版迁移到稳定版并且一些语法发生了变化,如果有人遇到同样的错误,你可以从以下链接获得解决方案 - https://firebase.google.com/docs/functions/beta-v1-diff

MAYANK SINGH
2020-08-01