【问题标题】:Getting a field from one Cloud Firestore document to specify the location for which to listen for changes (or writes) in another Cloud Function从一个 Cloud Firestore 文档中获取一个字段以指定在另一个 Cloud Function 中侦听更改(或写入)的位置
【发布时间】:2020-04-27 01:49:19
【问题描述】:

我已成功使用 Typescript 中的 Firebase Cloud Function 在创建 Firestore 集合中的文档时向用户发送通知。

但是,因为我将同一个文档存储在两个不同的位置,所以它会发送两次通知。我希望只发送一次通知。

有没有办法使用另一个云函数来获取当前用户,然后在查询中使用它来发送通知的我的函数,因此它只查找针对该特定用户发生的更改中的写入/读取只要?

这是我在 Cloud Functions 中的代码:

export const notificationOnMessageReceived = 
functions.firestore
    .document('users/{uid}/matches/{match}/messages/{message}') //HOW CAN I GET UID FROM ANOTHER FUNCTION AND USE IT HERE TO SPECIFY EXACTLY THE USER FOR WHICH IT SHOULD RUN?
    .onCreate(async snapshot => {

        const message = snapshot.get('Message');

        const token = snapshot.get('Device token receiver'); 

        console.log('token: ' + token); 

        const payload = {
            notification: {
                title: `New message`,
                body: `${message}`
            }
        };

        return fcm.sendToDevice(token, payload);
    });

【问题讨论】:

  • 您能否详细说明您到底想做什么。 “我可以得到uid”:你的意思是users/{uid}/matches/{match}/messages/{message}下创建文档的用户的uidOR这个路径中uid的值?无论如何,您很可能应该能够在一个 Cloud Function 中完成所有处理。但我们需要更准确的细节来帮助您!
  • 如果我得到在 users/{uid}/matches/{match}/messages/{message} 下创建文档的用户,它仍然会运行两次,因为同一个用户创建了两个文档。所以这行不通。如果我可以在路径中获取 uid 并且只为一个用户运行该代码,那么这将解决问题。现在因为 {uid} 未定义,它为两个用户运行。

标签: typescript firebase google-cloud-firestore google-cloud-functions


【解决方案1】:

我可以看到两种可能性:

1。在文档中写下作者uid

如果你可以在两个文档中写上作者的uid,在你的云函数中你可以检查这个uid是否对应路径的uid。

类似于以下内容:

export const notificationOnMessageReceived = 
functions.firestore
    .document('users/{uid}/matches/{match}/messages/{message}') 
    .onCreate(async (snapshot, context) => {

         const newValue = snapshot.data();
         const authorId = newValue.authorId;

         const pathUid = context.params.uid;

         if (authorId === pathUid) {
         
             //proceed with the notification
 
         } else {
            return null;
         }

    })

当然,这意味着每次“白费”都会触发一次云功能。关于 Cloud Function 调用的价格,这是可以接受的。

2。在专用集合中编写额外的文档

这样,只有一个文档会触发云函数,但缺点显然是额外的写入。在价格方面,它高于之前的解决方案(基于 Blaze Plan pricing)。您可以定期触发删除已处理文档的计划 Cloud Function。


旁注:您显然使用的是旧版本的 Firebase SDK for Cloud Functions,请参阅 https://firebase.google.com/docs/functions/beta-v1-diff#cloud-firestore。从 SDK 1.0 版开始,Firestore 异步函数的 event 参数已过时。它已被两个新参数取代:snapshotcontext

【讨论】:

  • 谢谢。我不得不从这个例子中稍微调整一下代码,但总的来说这个解决方案有效:-)
猜你喜欢
  • 2019-08-13
  • 2018-03-17
  • 2018-08-24
  • 1970-01-01
  • 2018-02-24
  • 2018-06-30
  • 1970-01-01
  • 2021-01-24
  • 2021-06-24
相关资源
最近更新 更多