首页 > 解决方案 > 使用 Firebase 云功能有条件地发送通知?

问题描述

我正在编写一个 android 应用程序,我需要根据某些条件发送通知。

在此处输入图像描述

例如,当然notiType = home后在通知中发送其他消息。如果notiType = inBetween然后发送另一条消息

我为此编写了云功能,但在部署时出错。

这是云功能:

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

/* Listens for new messages added to /messages/:pushId and sends a notification to users */
exports.pushNotification = functions.database.ref('/Notifications/{user_id}/{notification_id}').onWrite(event => {
  console.log('Push notification event triggered');
  /* Grab the current value of what was written to the Realtime Database 
   */
  const userId = event.params.user_id;
  const notificationId = event.params.notification_id;


  const deviceToken = admin.database().ref(`Notifications/${userId}/${notificationId}/deviceToken`).once('value');
  const childName = admin.database().ref(`Notifications/${userId}/${notificationId}/childName`).once('value');
  const notificationType = admin.database().ref(`Notifications/${userId}/${notificationId}/type`).once('value');

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

    const token = result[0].val();
    const name = result[1].val();
    const type = result[2].val();

    /* Create a notification and data payload. They contain the notification information, and message to be sent respectively */

    const payload;

    switch (type) {
      case "home":
        payload = {
          notification: {
            title: 'App Name',
            body: `${name} is reached at home`,
            sound: "default"
          }
        };
        break;
      case "between":
        payload = {
          notification: {
            title: 'App Name',
            body: `${name} stuck on the way for some reason`,
            sound: "default"
          }
        };
        break;
      case "school":
        payload = {
          notification: {
            title: 'App Name',
            body: `${name} reached at school`,
            sound: "default"
          }
        };
        break;
    };

    return admin.messaging().sendToDevice(token, payload).then(response => {
      return null;
    });
  });
});

收到此错误:

收到此错误

请纠正我哪里出错了。使用 Firebase -tools 版本 5.0.1

标签: javascriptfirebasefirebase-cloud-messaginggoogle-cloud-functions

解决方案


JavaScript 告诉你这一行是无效的:

const payload;

如果不立即给它一个值,你就不能声明一个 const 变量。由于您稍后有条件地给它一个值,也许您应该let payload;改用它。


推荐阅读