如何监测特定用户是否创建了新文档

huangapple go评论60阅读模式
英文:

How to monitor if new document is created for specific user

问题

我应该如何将ID传递给上面的Cloud Functions代码,而ID是当前用户ID或用户名?
目前,认证是在应用程序中完成的,用户登录应用程序,但我不确定服务器上的Cloud Functions如何知道是哪个用户登录并与应用程序交互?
我只需要监视相关用户的“onCreate”事件。

英文:

Say we have the following code in Cloud Functions Typescript code:

functions.firestore.document("collectionName/"+ID).onCreate(...

How am I supposed to pass ID to Cloud Functions code above while ID is the current user ID or username?
Currently the authentication is done in the app and user enters the app, but I am not sure how Cloud Functions on the server can know who is this user who logged in and interacts with the app?

I need to monitor "onCreate" event only for the relevant user.

答案1

得分: 2

你不需要将任何内容“传递”给Firestore的onCreate触发器。它只会在匹配的文档创建时运行,你需要指定要匹配的文档模式。当创建匹配的文档时,该函数会运行,并且你可以使用提供的context来获取被创建的文档的ID。

我建议查看文档中的一个onCreate触发器的示例:

exports.createUser = functions.firestore
    .document('users/{userId}')
    .onCreate((snap, context) => { ... }

在上面提供的示例中,触发器匹配了用户集合中的所有文档。userId通配符包含了匹配的ID。你可以使用它来获取创建的文档的ID。使用通配符的文档,你可以从传递给函数的context参数中获取ID。

以下是文档中使用onWrite触发器的示例:

exports.useWildcard = functions.firestore
    .document('users/{userId}')
    .onWrite((change, context) => {
      // 如果我们将`/users/marie`设置为{name: "Marie"},
      // 那么context.params.userId == "marie"
      // ... 并且 ...
      // change.after.data() == {name: "Marie"}
    });
英文:

You don't "pass" anything to a Firestore onCreate trigger. It just runs any time a matching document is created. You have to specify the pattern of the documents to match. When a matching document is created, the function runs, and you can use the provided context to know the ID of the document that was created.

I suggest reviewing the documentation for an example of an onCreate trigger:

exports.createUser = functions.firestore
    .document('users/{userId}')
    .onCreate((snap, context) => { ... }

In the provided example above, the trigger matches all documents in the users collection. The userId wildcard contains the ID that was matched. You can use that to know the ID of the document that was created. Using the documentation for wildcards you can get the ID from the context parameter passed to the function.

Here is the example from the documentation that uses an onWrite trigger:

exports.useWildcard = functions.firestore
    .document('users/{userId}')
    .onWrite((change, context) => {
      // If we set `/users/marie` to {name: "Marie"} then
      // context.params.userId == "marie"
      // ... and ...
      // change.after.data() == {name: "Marie"}
    });

huangapple
  • 本文由 发表于 2023年5月20日 20:34:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76295259.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定