Firebase Cloud Functions获取更新的文档详细信息

时间:2019-08-24 06:22:42

标签: node.js firebase google-cloud-firestore google-cloud-functions

我正在尝试编写一个云函数,如果我的应用更改了用户的Firestore数据库中的某些字符串,该函数将在其中。云功能需要发送推送通知。数据库体系结构是消息=> {UID} => UpdatedMessages 。问题是我无法弄清楚如何检索更新了 UID 的哪个 updateMessage

  const functions = require('firebase-functions');
const admin = require('firebase-admin')
admin.initializeApp()
const toUpperCase = (string)=> string.toUpperCase()
var registrationToken = 'dfJY6hYzJyE:APdfsdfsdddfdfGt9HMfTXmei4QFtO0u1ePVpNYaOqZ1rnDpB8xfSjx7-G6tFY-vWQY3vDPEwn_iZVK2PrsGUVB0q9L_QoRYpLJ3_6l1SVHd_0gQxJb_Kq-IBlavyJCkgkIZ';
exports.sendNotification  = functions.firestore
    .document('messages/{userId}/{updatedMessage}')
    .onUpdate((change, context) => {

var message = {
  data: {
    title: 'Update',
    body: 'New Update'
  },
  token: registrationToken
};

// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent messagesssss:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });
    });

仅我需要从UID中获取“ var registrationToken”。

1 个答案:

答案 0 :(得分:1)

您必须如下使用params对象的context属性

exports.sendNotification  = functions.firestore
    .document('messages/{userId}/{updatedMessage}')
    .onUpdate((change, context) => {


    const userId = context.params.userId;
    const updatedMessage = context.params.updatedMessage;

    var message = {
       data: {
          title: 'Update',
          body: updatedMessage //For example, use the value of updatedMessage here
       },
       //...
    };

    //IMPORTANT: don't forget to return the promise returned by the asynchronous send() method
    return admin.messaging().send(message)
    .then((response) => {
        // Response is a message ID string.
        console.log('Successfully sent messagesssss:', response);
        return null;
      })
      .catch((error) => {
        console.log('Error sending message:', error);
        return null;
      });


});

有关更多信息,请参见https://firebase.google.com/docs/functions/firestore-events#wildcards-parametershttps://firebase.google.com/docs/reference/functions/functions.EventContext#params


关于上面代码中标记为“重要”的注释,您可以在此处观看官方的Firebase视频系列:https://firebase.google.com/docs/functions/video-series/。尤其要观看三个名为“学习JavaScript的承诺”的视频(第2和第3部分特别关注后台触发的Cloud Functions,但之前确实值得观看第1部分)。