如何使用firestore在node.js中获取Google云函数执行事件

问题描述 投票:0回答:2

下面是谷歌云功能,部署正确并且工作正常 函数路径 -functions/index.js

const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp();

exports.createUser = functions.firestore
.document('users/{userId}')
.onCreate((snap, context) => {
    const newValue = snap.data();
    console.log(newValue);
});

如何在 Node.js 应用程序中成功调用时访问此函数的事件 像

这样的东西
const myFunctions = require("./functions/index");

myFunctions.createUser().then((data) => {
    console.log(data)
})
.catch((err) => {
    console.log(err);
})

截至目前出现以下错误

firebase google-cloud-platform google-cloud-firestore firebase-realtime-database google-cloud-functions
2个回答
1
投票

您的

createUser
云功能由 Firestore
onCreate()
事件类型触发,因此根据 文档,将“在首次写入文档时触发”。

该文档还添加了以下内容:

在典型的生命周期中,Cloud Firestore 函数会执行以下操作:

  1. 等待特定文档的更改。 (这里是第一次写文档的时候)

  2. 事件发生时触发并执行其任务

  3. 接收一个数据对象,其中包含指定文档中存储的数据的快照。

因此,如果您想从“外界”触发此云功能,例如:在 Node.js 应用程序中,您需要在相应位置(即在

users
集合下)创建一个新的 Firestore 文档。为此,您将使用 Node.js Server SDK,请参阅 https://cloud.google.com/nodejs/docs/reference/firestore/0.14.x/

请注意,您还可以通过使用相应的客户端 SDK 创建新的

user
文档,从客户端应用程序(Web、Android、iOS)触发它。


更新您的评论:

您无法直接“移植”并运行为 Cloud Functions 编写的代码到 Node.js 应用程序。您将必须重新开发 Node.js 解决方案。

在您的情况下,您应该使用 Node.js Server SDK(如我的评论中提到的),并且您可以使用 CollectionReference 的

onSnapshot
方法。请参阅 https://cloud.google.com/nodejs/docs/reference/firestore/0.14.x/CollectionReference#onSnapshot


0
投票

我会尝试回答你的问题,但有点不清楚。你问:

如何获取Google云函数执行事件

好吧,当函数触发并且您的代码正在运行时,事件就开始了,即您的行

const newValue = snap.data()

也许您正在寻找一种在触发器运行时执行某些任务的方法?您只需从函数内部执行此操作,然后返回一个承诺即可。例如,如果您要运行多个异步任务,则可以使用 Promise.all([])。

© www.soinside.com 2019 - 2024. All rights reserved.