【问题标题】:Firebase Cloud Functions get updated document DetailsFirebase Cloud Functions 获取更新的文档详细信息
【发布时间】:2019-08-24 06:22:42
【问题描述】:

我正在尝试编写一个云函数,如果我的应用程序更改了用户的 firestore 数据库中的某些字符串。云功能需要发送推送通知。数据库架构是 Messages => {UID} => UpdatedMessages 。问题是我不知道如何检索哪个 updateMessage 在哪个 UID 下已更新。

  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”。

【问题讨论】:

  • 如果你已经想触发一个云函数,为什么不首先调用你的云函数来写入你的数据库?
  • 我知道你正在使用 firestore,但也许这对你有帮助 youtube.com/…
  • 谢谢康斯坦丁啤酒。我想我会使用云函数在我的数据库上写。这样发送推送通知更容易
  • 你怎么不知道哪条消息被编辑了?只需在/messages/节点下的onEdit触发你的函数,就可以得到编辑消息的整个路径
  • @Emanuele 谢谢你不知道这是可能的

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


【解决方案1】:

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

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 了解更多信息。


关于上述代码中标注为“IMPORTANT”的备注,您可以在此处观看 Firebase 官方视频系列:https://firebase.google.com/docs/functions/video-series/。特别是观看名为“学习 JavaScript Promises”的三个视频(第 2 部分和第 3 部分特别关注背景触发的云函数,但之前确实值得观看第 1 部分)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多