当用户将另一个用户添加为朋友时,尝试发送推送通知

时间:2017-11-14 21:50:17

标签: node.js firebase push-notification google-cloud-platform

我正在尝试设置云功能以向接收用户发送通知,但是当我查看我的日志时,它显示未定义的friendRequest.sender。在firebase云函数中访问嵌套json值的正确方法是什么?

exports.sendFriendRequestNotification = functions.database.ref('/friend_request/{pushId}').onWrite(event => {
 var friendRequestMessage = "Sent you a friend request";

 const friendRequest = event.data.current.val();
 console.log(friendRequest);

 const senderUid = event.data.current.child("sender").child("userId").val();
 const receiverUid = event.data.current.child("receiver").child("userId").val();

 console.log(senderUid); //getting null in fb logs


 const promises = [];

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

 const getInstanceIdPromise = admin.database().ref('/friend_request/{pushId}').once('value');
 const getReceiverUidPromise = admin.auth().getUser(receiverUid);

 return Promise.all([getInstanceIdPromise, getReceiverUidPromise]).then(results => {
     const instanceId = results[0].val();
     const receiver = results[1];
     console.log('notifying ' + receiverUid + ' about ' + friendRequestMessage + ' from ' + senderUid);

     const payload = {
         notification: {
             title: receiver.displayName,
             body: friendRequestMessage,
             icon: receiver.photoURL
            }
    };

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

});

});

我的朋友请求对象

           { '-KyYOqdAJAi5tKv3rMIY': { receiver: 
  { soundCloudUserId: 0,
    userId: 'RvMaDClGqohUHrYDgKp9u5i03OI3  ',
    userName: 'fakefriend' },
 sender: 
  { soundCloudUserId: 0,
    userId: 'VqDgYnDMNVUtByH3uyLDNskPPlj1 ',
    userName: 'doug4less' },
 status: 'Pending' } }

以下是数据在我的Firebase数据库中的显示方式

friend_request 
      -> VqDgYnDMNVUtByH3uyLDNskPPlj1 
          -> -KzPS5JjFE51hoqAP6_m
              -> receiver ...
                 sender   ...
                 status: "pending"

以下是我如何创建好友请求

    public void addFriendRequest() {
    BrainBeatsUser sender = new BrainBeatsUser("VqDgYnDMNVUtByH3uyLDNskPPlj1 ", "doug4less");
    BrainBeatsUser receiver = new BrainBeatsUser("RvMaDClGqohUHrYDgKp9u5i03OI3  ", "fakefriend");

    DatabaseReference friendRequest = mFirebaseDatabase.getReference("friend_request/" + mAddUser.getUserId());
    friendRequest
            .push()
            .setValue(new FriendRequest("Pending", sender, receiver))
            .addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    friendUserDialog.dismiss();
                    Constants.buildInfoDialog(SocialActivity.this, "Request Sent", "Your friend request has been sent.");
                    sendFriendNotification();
                } else {
                    Constants.buildInfoDialog(SocialActivity.this, "Error", "There was an issue when sending that request.");
                }
            });
}

1 个答案:

答案 0 :(得分:0)

试试这个:

 const senderUid = event.data.current.child("sender").child("userId").val();
 const receiverUid = event.data.current.child("receiver").child("userId").val();

event.data.current是一个DeltaSnapshot对象,您需要使用这样的语法来访问它的子对象。