【问题标题】:Get Data from Firestore before Schedule a Cloud Function在安排云功能之前从 Firestore 获取数据
【发布时间】:2020-06-19 23:23:07
【问题描述】:

我无法从文档中获取数据并使用该文档中的单个字段作为我的调度 Cloud Function 的参数,首先我尝试获取文档,然后调用 getData() 函数并使用该变量从中调用 .data 并且我正在等待调用 .get() ,但我仍然收到此错误。

“Promise>”类型上不存在属性“数据”。

我不能打电话给await getData();,因为我收到了这个错误

仅当 'module' 选项设置为 'esnext' 或 'system' 并且 'target' 选项设置为 'es2017' 或更高版本时,才允许使用顶级 'await' 表达式。

有什么办法吗?我需要首先获取包含我将运行计划函数的月份中的哪一天的数据。

这是我的代码:

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";

/// Get the config data for schedule time and debt payment
async function getData() {
  return await admin.firestore().doc("neighbors/0000_admin").get();
}

const configData = getData();

/// Updates the debt for each neighbor on a specific day of each month
export const debtUpdatePerMonth = functions.pubsub
  .schedule(`${configData?.data()?.day_of_month_to_pay} of month 06:00`)
  .onRun(async (context) => {

    return admin
      .firestore()
      .collection("neighbors")
      .get()
      .then((snapshot) => {
        snapshot.forEach((doc) => {
          return doc.ref.update({
            debt: doc.data()?.debt + configData?.data()?.monthly_pay,
          });
        });
      });
  });

提前致谢

【问题讨论】:

  • 您的代码中有两个对getData() 的调用,一个在顶层,一个在函数内部。他们都试图分配给同一个命名变量。这让我很困惑。如图所示,错误消息不可能指的是其中任何一个。你能解释一下为什么需要两次调用,尤其是函数外顶层的调用吗?
  • 对不起,Doug,这是我的错,我的日程安排中的 getData() 调用是第一次尝试,我忘了删除它,实际上我日程安排中的调用确实有效,我可以获取数据我需要那里,但是因为我得到两条信息,一条在debt: doc.data()?.debt + configData?.data()?.monthly_pay, 中使用,另一条应该用作一个月中的一天:`.schedule(${configData?.data()?.day_of_month_to_pay} of month 06:00)`,这就是我为什么想在schedule之前调用,忘记删了里面的,我现在编辑一下

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


【解决方案1】:

没有办法根据动态加载的数据声明云函数,就像您在这里尝试做的那样:

/// Get the config data for schedule time and debt payment
async function getData() {
  return await admin.firestore().doc("neighbors/0000_admin").get();
}

const configData = getData();

/// Updates the debt for each neighbor on a specific day of each month
export const debtUpdatePerMonth = functions.pubsub
  .schedule(`${configData?.data()?.day_of_month_to_pay} of month 06:00`)
  .onRun(async (context) => {
    ...

在部署时必须知道触发云功能的计划。

您可以使用 Cloud Tasks 完成您想要做的事情。现在您的主要调用将是一个可调用(或 HTTPS)函数,然后该代码会安排 Cloud Tasks。然后,这些 Cloud Tasks 会调用您当前的 onRun 函数。

Doug 写了一篇很棒的博文:How to schedule a Cloud Function to run in the future with Cloud Tasks (to build a Firestore document TTL)

【讨论】:

  • 谢谢弗兰克!这对我来说是一个新主题,我将深入研究该文档:)
  • 另一个相关的问题,是否有一个选项可以在 onWrite 触发函数内部运行调度函数?例如,如果文档的某个字段发生更改,那么程序会在该字段更改时安排一个新函数?那么是否可以选择在另一个函数中调用函数?提前致谢
  • 如果您想动态调度 Cloud Functions,您需要采用 Cloud Tasks 的方法。我有时会在我的代码中通过一个简单的setTimeout() 进行短暂的延迟(最多 60 秒),但不一定建议这样做(因为您最终会为没有发生任何事情的时间付费)。
猜你喜欢
  • 2018-06-30
  • 2021-05-06
  • 2018-04-18
  • 2020-03-12
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
  • 2020-05-10
相关资源
最近更新 更多