Firebase 云功能不对 Xstate 做任何事情

Firebase cloud function not doing anything with Xstate

我正在尝试在 Firebase 上编写一个云函数,以便在编写另一个文档时更新 Firebase 中的一个文档。为此,我使用触发方法 onWrite。我为此使用 Xstate,因为我的原始代码更复杂,但想法是一样的(问题也是如此)。这是我使用的代码(打字稿):

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
import { Machine, interpret } from "xstate";

admin.initializeApp({});

// This function will trigger as soon as a product of a company owner gets updated.
exports.productsOnUpdate = functions.firestore
  .document(`companies/{companyId}/{products}/{productId}`)
  .onWrite((change: any) => {

    let done = false;

    const PromiseFunction = (docIn: any) => {
      console.log(docIn);
      return admin
        .firestore()
        .collection("test")
        .doc("testdoc")
        .set({ products: docIn.products }, { merge: true })
        .then((doc: FirebaseFirestore.WriteResult) => doc.writeTime);
    };

    const myMachine = Machine<any>({
      id: "myMachine",
      initial: "idle",
      context: { doc: { products: "a product" } },
      states: {
        idle: {
          on: {
            INIT: "init"
          }
        },
        init: {
          invoke: {
            id: "setDoc",
            src: (context, event) => PromiseFunction(context.doc),
            onDone: {
              target: "success"
            },
            onError: {
              target: "failure"
            }
          }
        },

        success: {},
        failure: {}
      }
    }); // end of machine

    const MyMachine = interpret(myMachine).onTransition(state => {
      console.log(state.value);
      // actually do something here
      switch (state.value) {
        case "INIT":
          break;

        case "success":
          done = true;
          console.log("Success");

        case "failure":
          console.log("Something went wrong");

        default:
          break;
      }
    });

    MyMachine.start();
    MyMachine.send("INIT");
    while (done === false);
    return "ok";
  });

因此,当尝试更新子集合 'products' 中的文档时,这应该会触发该函数。在日志中,我看到以下内容:

绝对没有任何反应。当我在 MyMachine 的上下文中犯了一个小错误(将 context: { doc: { products: "a product" } } 更改为 context: { doc: { product: "a product" } }, 我确实看到了这个:

所以承诺处理似乎有问题。我已经在这上面花了一天时间;感谢您的帮助!

你应该让 xstate 兑现你的承诺。从 PromiseFunction:

中删除 then 语句

const PromiseFunction = (docIn: any) => {
  console.log(docIn);
  return admin
    .firestore()
    .collection("test")
    .doc("testdoc")
    .set({ products: docIn.products }, { merge: true })
};

onDone

中处理已解决的 Promise

onDone: {
  target: "success",
  actions: (ctx, e) => console.log(e), // do stuff with your resolved Promise
}