云功能中的云消息传递:admin.messagin(...)。send不是一个功能

时间:2018-02-20 21:33:02

标签: node.js firebase firebase-cloud-messaging google-cloud-functions firebase-admin

我的功能由数据库事件触发,并使用Firebase云消息传递向主题发送通知。我的第一个函数运行正常,但第二个函数不断抛出此错误:

2018-02-20T21:16:49.878Z E receiveMessage: TypeError: admin.messaging(...).send is not a function
at exports.receiveMessage.functions.database.ref.onCreate (/user_code/index.js:55:27)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:59:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:53:36)
at /var/tmp/worker/worker.js:695:26
at process._tickDomainCallback (internal/process/next_tick.js:135:7)

这是index.js文件:

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

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
//  response.send("Hello from Firebase!");
// });
exports.recceiveInvitation = /* the function that works */;

exports.receiveMessage = functions.database.ref('/messages/{chatId}/{time}').onCreate((event) => {
    const chatId = event.params.chatId;
    console.log('messages', chatId);
    var sender = event.data.val().name;
    var messageContent = event.data.val().message;
    if(messageContent.length >= 100){
        messageContent = messageContent.substring(0,97)+"...";
    }
    const payload = {
        data: {
            title: `New Message from ${sender}`,
            body: messageContent
        },
        topic: chatId
    };

    return admin.messaging().send(payload);
});

我运行了npm install firebase-admin,但我没有帮助。

2 个答案:

答案 0 :(得分:7)

改变这个:

return admin.messaging().send(payload);

到此:

return admin.messaging().sendToTopic(topicname,payload);

能够向主题发送通知。

您可以执行上述操作,或查看下面的注释

注意:

您需要更新firebase-admin npm包,才能使用send()

enter image description here

npm install firebase-admin@latest

更多信息: -

https://firebase.google.com/support/release-notes/admin/node https://firebase.google.com/docs/cloud-messaging/admin/send-messages

答案 1 :(得分:0)

let message = {notification: {title: "your title",body: "your message",},token:"token of user device"
      };

admin.messaging().send(message)