Firebase管理员会将通知发送到nodejs中的其他服务帐户

时间:2018-05-13 04:20:37

标签: node.js express firebase-cloud-messaging firebase-admin

我在nodejs中有两条路线。 一个是这样的,one.js

var admin = require("firebase-admin");
var topic = "/topics/news";

var serviceAccount = require("/path/serice-1-firebase-adminsdk.json");

var firebase = admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://service-1-database.firebaseio.com/"
});

console.log(firebase.name);

然后我发送这样的通知

router.post('/', function(req, res) {
  var payload = {
    data: {
      title: req.body.title,
      message: req.body.message
    }
  };
  admin.messaging().sendToDevice(topic, payload)
    .then(function(response) {

      console.log("value of topic ", topic);
      console.log("Successfully sent message:", response);
    })
    .catch(function(error) {
      console.log("Error sending message:", error);
    });

});

在另一条路线中,两个.js,我正在做这个

var admin = require("firebase-admin");
var topic = "/topics/news";
var serviceAccount = require("path/service-2-firebase-adminsdk.json");

var firebase = admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://service-2-database.firebaseio.com"
},"other");
console.log(firebase.name);

然后我再次发送这样的通知

router.post('/notify',function(req,res){
  var category = req.body.category;

      var payload = {
        data: {
          title: "title",
          message: "desc"
        }
      };


      admin.messaging().sendToDevice(topic, payload)
        .then(function(response) {
          console.log("value of topic ", topic);
          console.log("Successfully sent message:", response);
        })
        .catch(function(error) {
          console.log("Error sending message:", error);
        });

});

当我尝试使用two.js为service-2发送通知时,通知将被发送到service-1,但两个服务帐户是service-2。我错过了什么?

1 个答案:

答案 0 :(得分:0)

admin.messaging()始终引用默认应用的messaging命名空间。在您的情况下,默认应用是在one.js中初始化的应用。所以观察到的行为是正确的。要使用自定义应用发送通知,您必须执行以下操作:

const otherApp = admin.app('other');
admin.messaging(otherApp).sendToDevice(...);