event.params.wildcard返回错误的值

时间:2017-05-18 17:32:40

标签: javascript firebase firebase-cloud-messaging

我有一个非常简单的firebase功能:

exports.sendFollowNotification = functions.database.ref('PendingRequest/{receiver_id}/{sender_id}').onWrite(requestEvent => {
    const requestSnapShot = requestEvent.data;
    const senderId = requestEvent.params.sender_id;
    const targetId = requestEvent.params.receiver_id;

    const target_token = requestSnapShot.child('sender').val();
    const sender_token = requestSnapShot.child('receiver').val();
    console.log('sender_id :'+senderId);
    console.log('target_id :'+targetId); 
    console.log('target_token: '+ target_token);
    console.log('sender_token: '+sender_token);

    const pendingRequestPayload = {
        data: {
            token_sender : sender_token,
            token_target : target_token,
            request_sender : senderId,
            request_receiver : targetId,                
            my_message_id: '0'
        }
    };

    if(target_token != null){   

     // Send a message to devices subscribed to the provided topic.
    return admin.messaging().sendToDevice(target_token, pendingRequestPayload)
        .then(function (response) {
            // See the MessagingTopicResponse reference documentation for the
            // contents of response.
            console.log("Successfully sent message:", response);
        })
        .catch(function (error) {
            console.log("Error sending message:", error);
        });

    }    

每当此函数触发时,有两个值被交换:senderId获取targetId值,反之亦然。使用params属性检索这两个值,而我从requestSnapShot.child('value_name')获取的值没有任何异常.val();
愚蠢的解决方案只是在需要时交换这两个值,但是,这是一个非常愚蠢的解决方案。我在这里错过了什么?

1 个答案:

答案 0 :(得分:0)

如果“target”是“receiver”,则交换它们:

const target_token = requestSnapShot.child('sender').val();
const sender_token = requestSnapShot.child('receiver').val();

您是否故意这样做以解决问题?

<强>更新

很难猜出为什么这不适合你。我复制了你的代码,消除了你的解决方法,并缩短了它以进行测试:

exports.sendFollowNotification = functions.database.ref('PendingRequest/{receiver_id}/{sender_id}')
       .onWrite(requestEvent => {
    const requestSnapShot = requestEvent.data;
    const senderId = requestEvent.params.sender_id;
    const targetId = requestEvent.params.receiver_id;

    const target_token = requestSnapShot.child('receiver').val();
    const sender_token = requestSnapShot.child('sender').val();
    console.log('sender_id :'+senderId);
    console.log('target_id :'+targetId);
    console.log('target_token: '+ target_token);
    console.log('sender_token: '+sender_token);
});

掌握这些数据:

{
  "PendingRequest" : {
    "R1" : {
      "S1" : {
        "receiver" : "R-token",
        "sender" : "S-token"
      }
    }
  }
}

得到了这个日志输出:

sender_token: S-token
target_token: R-token
target_id :R1
sender_id :S1