1

我试图在添加新帖子时将通知推送到Android应用程序。但是,无论何时数据被“更改”,即使删除了我不需要的帖子,通知都会到达。我怎样才能把条件,使FCM发送通知只有当帖子被添加。这里是我的index.js文件确定是否将数据添加或删除到Firebase实时数据库

const functions = require('firebase-functions'); 
let admin = require('firebase-admin'); 
admin.initializeApp(functions.config().firebase); 
exports.sendPush = functions.database.ref('/promos').onWrite(event => { 
var topic = "deals_notification"; 
let projectStateChanged = false; 
let projectCreated = true; 
let projectData = event.data.val(); 
if (!event.data.previous.exists()) { 
    // Do things here if project didn't exists before 
} 
if (projectCreated && event.data.changed()) { 
    projectStateChanged = true; 
} 
let msg = ""; 
if (projectCreated) { 
    msg = "A project state was changed"; 
} 
if (!event.data.exists()) { 
    return; 
    } 
let payload = { 
     notification: { 
      title: 'Firebase Notification', 
      body: msg, 
      sound: 'default', 
      badge: '1' 
     } 
}; 

admin.messaging().sendToTopic(topic, payload).then(function(response) { 
// See the MessagingTopicResponse reference documentation for the 
// contents of response. 
console.log("Successfully sent message:", response); 
}).catch(function(error) { 
console.log("Error sending message:", error); 
}); 
}); 

回答

0

你做错了两两件事:每当任何数据/promos下写

  • 您的功能现在触发。无论何时写入特定促销,您都希望它被触发:/promo/{promoid}

  • 你完全无视数据是否已经存在:if (!event.data.previous.exists()) {,所以需要将其连接起来。

所以更接近于这样的:

const functions = require('firebase-functions'); 
let admin = require('firebase-admin'); 
admin.initializeApp(functions.config().firebase); 
exports.sendPush = functions.database.ref('/promos/{promoId}').onWrite(event => { 
    if (!event.data.previous.exists()) { 
     let topic = "deals_notification"; 
     let payload = { 
      notification: { 
       title: 'Firebase Notification', 
       body: "A project state was changed", 
       sound: 'default', 
       badge: '1' 
      } 
     }; 

     return admin.messaging().sendToTopic(topic, payload); 
    } 
    return true; // signal that we're done, since we're not sending a message 
});