使用Firebase云功能有条件地发送通知吗?

时间:2019-07-10 14:39:43

标签: javascript firebase firebase-cloud-messaging google-cloud-functions

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

enter image description here

例如,当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} stucked 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;
    });
  });
});

遇到此错误:

Getting this error

请纠正我要去哪里的地方。使用Firebase -tools版本5.0.1

1 个答案:

答案 0 :(得分:1)

JavaScript告诉您此行无效:

const payload;

您不能在不立即为其提供值的情况下声明const变量。由于您稍后将有条件地为其提供值,因此也许应该改用let payload;

相关问题