javascript – Firebase功能,用于从Firebase DB获取数据以进行推送通知

前端之家收集整理的这篇文章主要介绍了javascript – Firebase功能,用于从Firebase DB获取数据以进行推送通知前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我与firebase数据库和Firebase云消息传递聊天应用程序.我可以通过控制台发送firebase通知,但在实际情况下,它应该是自动的.为了进行自动通知,我的朋友为我写了Index.js(在云函数添加)文件,但它没有发送通知.

根据我们的逻辑函数,只要有任何新条目(在任何节点或任何房间)都应该触发,并通过firebase函数获取这些值,并向FCM服务器发出post请求以通知接收方设备(从token_To获取接收方设备的值) ).

>消息
> Message_From
>时间
>类型
> token_To

Index.js

var functions = require('firebase-functions');
var admin = require('firebase-admin');


var serviceAccount = require('./demofcm-78aad-firebase-adminsdk-4v1ot-2764e7b580.json');
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),databaseURL: "https://demofcm-78aad.firebaseio.com/"
})

// // 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.setUserNode = functions.auth.user().onCreate(event => {
  // ...
});

exports.notifyMsg = functions.database.ref('/{chatroom}/{mid}/')
    .onWrite(event => {

       if (!event.data.val()) {
         return console.log('Message Deleted');
       }

       const getDeviceTokensPromise = admin.database().ref('/{chatroom}/{mid}/token_to').once('value');


       return Promise.all([getDeviceTokensPromise]).then(results => {
         const tokensSnapshot = results[0];

         if (!tokensSnapshot.hasChildren()) {
           return console.log('There are no notification tokens to send to.');
         }

         const payload = {
           notification: {
             title: 'You have a new Message!',body: event.data.val().Message
           }
         };

         const tokens = Object.keys(tokensSnapshot.val());

         return admin.messaging().sendToDevice(tokens,payload).then(response => {

           const tokensToRemove = [];
           response.results.forEach((result,index) => {
             const error = result.error;
             if (error) {
               console.error('Failure sending notification to',tokens[index],error);

               if (error.code === 'messaging/invalid-registration-token' ||
                   error.code === 'messaging/registration-token-not-registered') {
                 tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
               }
             }
           });
           return Promise.all(tokensToRemove);
         });
       });
});

Firebase功能日志

如何从数据库获取同一房间(9810012321-9810012347)或任何其他房间(9810012321-9810012325)中任何新添加节点的上述值,并将其发送给FCM进行通知

提前致谢.

解决方法

我所做的是创建一个Message节点,我相信用户密钥可以做到这一点.即,使接收者(toId)和发送者(fromId)键发送通知.
希望能帮助到你.

exports.sendMessageNotification = functions.database.ref('/messages/{pushId}')
.onWrite(event => {
    let message = event.data.current.val();
    console.log('Fetched message',event.data.current.val());
    let senderUid = message.fromId;
    let receiverUid = message.toId;
    let promises = [];

    console.log('message fromId',receiverUid);
    console.log('catch me',admin.database().ref(`/users/${receiverUid}`).once('value'));

    if (senderUid == receiverUid) {
        //if sender is receiver,don't send notification
        //promises.push(event.data.current.ref.remove());
        return Promise.all(promises);
    }

    let messageStats = message.messageStatus;
    console.log('message Status',messageStats);

    if (messageStats == "read") {
        return Promise.all(promises);
    }

    let getInstanceIdPromise = admin.database().ref(`/users/${receiverUid}/pushToken`).once('value');
    let getSenderUidPromise = admin.auth().getUser(senderUid);

    return Promise.all([getInstanceIdPromise,getSenderUidPromise]).then(results => {
        let instanceId = results[0].val();
        let sender = results[1];
        console.log('notifying ' + receiverUid + ' about ' + message.text + ' from ' + senderUid);
        console.log('Sender ',sender);
        var badgeCount = 1;
        let payload = {
            notification: {
                uid: sender.uid,title: 'New message from' + ' ' + sender.displayName,body: message.text,sound: 'default',badge: badgeCount.toString()
            },'data': { 
                'notificationType': "messaging",'uid': sender.uid
          }
        };
        badgeCount++;
        admin.messaging().sendToDevice(instanceId,payload)
            .then(function (response) {
                console.log("Successfully sent message:",response);
            })
            .catch(function (error) {
                console.log("Error sending message:",error);
            });
    });
});
原文链接:https://www.f2er.com/js/156604.html

猜你在找的JavaScript相关文章