firebase函数将通知推送给特定用户

时间:2017-11-14 11:53:12

标签: javascript firebase firebase-realtime-database google-cloud-functions

我想通过firebase函数向其他用户喜欢他/她的帖子发帖子的用户发送推送通知。

i want to get the highlighted user-id in the image to get fcm token of this user id stored in other tree.

这是我的firebase功能代码。

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


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


exports.sendNotification = functions.database.ref('/user-posts/{userID}/{pushId}/stars/')
        .onWrite(event=> {
            var request = event.data.val();

            console.log("request",request);
            console.log("key",Object.keys(request)[0]);
            var key = Object.keys(request)[0];
            var token;




            const payload = {
          notification: {
            title: 'You have a new follower!',
            body: 'is now following you.'
          }
        };



             const getDeviceTokensPromise = admin.database()
             .ref(`/users-notifications/${key}`)
             .once('value').then(function(snapshot) {
                    console.log("val",snapshot.val());
                        token= snapshot.val();


                        admin.messaging().sendToDevice(token,payload)
            .then(response=>{
                console.log("Successfully sent message:", response);

            })
            .catch(function(error){
                console.log("error sending message",error);
            })
        })

                    }, function(error) {
                        // The Promise was rejected.
                    console.error(error);
                    });

2 个答案:

答案 0 :(得分:0)

您可以使用event ref的父属性向后遍历数据库树。

userID = event.data.ref.parent.parent.parent.key
event.data.ref的父母是"明星" "明星"的父母是你的pushID pushID的父级是userID

答案 1 :(得分:0)

尝试使用event.params.userID

从uri中提取它