javascript - Firebase 实时数据库 fcm 消息发送问题

标签 javascript node.js firebase firebase-cloud-messaging google-cloud-functions

我是 Firebase 的新手,我一直在尝试制作一个发送/接收通知的 Android 应用程序。这段代码在几周前对我来说工作得很好,但现在它显示错误,尽管我没有做任何更改。

代码:

'use strict'

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

exports.pushNotification = functions.database.ref(`/notification/{user_id}/{notification_id}`).onWrite((change,context) =>{
    const user_id = context.params.user_id;
    const notification_id = context.params.notification_id;

    console.log('We have a notification to send',user_id);

    const deviceToken = admin.database().ref(`/users/${user_id}/tokenId`);
    const senderId = admin.database().ref(`/notification/${user_id}/${notification_id}/fromuser`);

    return Promise.all([deviceToken,senderId]).then(results =>{
        const tokensSnapshot = results[0];
        const sender = results[1];

        console.log("Device Token ID: ",tokensSnapshot.val());
        console.log("Sender ID: ",sender);

        const payload ={
            notification: {
                title: "New message",
                body: "hello",
                icon: "ic_launcher_round"
            }
        };
        return admin.messaging().sendToDevice(tokensSnapshot.val(),payload).then(response =>{
            response.results.forEach((result,index) =>{
                const error = result.error;
                if(error){
                    console.error('Failure sending notification to device',tokensSnapshot.val(),error);
                }
                else{
                    console.log('Notification sent to : ',tokensSnapshot.val());
                }
            });
            return null;
        });
    });
});

错误:

tokensSnapshot.val is not a function
    at Promise.all.then.results (/user_code/index.js:24:50)
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

最佳答案

我不希望您的代码能够正常工作。看看你在这里做什么:

const deviceToken = admin.database().ref(`/users/${user_id}/tokenId`);
const senderId = admin.database().ref(`/notification/${user_id}/${notification_id}/fromuser`);

return Promise.all([deviceToken,senderId]).then(results => { ... })

deviceTokensenderId 是数据库引用。它们只是指向数据库中的位置。但是,您将它们传递给 Promise.all(),就好像它们是 promise 一样。它们绝对不是 promise 。这意味着回调中的results 将不包含数据快照对象。

您需要查询数据库中的值并获取这些查询的 promise 。注意使用 once() 来查询引用:

const deviceToken =
    admin.database().ref(`/users/${user_id}/tokenId`).once('value');
const senderId =
    admin.database().ref(`/notification/${user_id}/${notification_id}/fromuser`).once('value');

once() 返回一个 promise ,该 promise 将通过引用位置的数据快照来解决。

在那之后,您的代码中还有更多需要解决的错误。特别是,您永远不会在 sender 上调用 val() 来获取您尝试查询的原始数据。之后您永远不会在任何地方使用发件人值(因此甚至查询它似乎毫无意义)。

关于javascript - Firebase 实时数据库 fcm 消息发送问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51810796/

相关文章:

javascript - 正则表达式 - 用一个替换多个 html 标签

javascript - node.js,测试 mongodb 保存和加载

java - 如何从 Firestore 查询中排除元素?

node.js - 如何修复 "gyp ERR! stack Error: Can' t 在 Windows 上找不到 Python 可执行文件 python?

node.js - Promise 返回未定义和之后的数据

firebase - 如何在 Flutter 中为 Firebase 身份验证手动触发 onAuthStateChanged?

firebase - 如何更新已全部插入列表的Map中的嵌套列表?例如。 List < map <字符串,动态>>

javascript - 这个 JavaScript 程序执行的步骤是什么

javascript - 隐藏/编码我的 javascript 代码

javascript - 扩展程序页面中的 Chrome 图标