我正在尝试在 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";
});
因此,当尝试更新子集合“产品”中的文档时,这应该会触发该功能。在日志中,我看到以下内容:
绝对没有任何反应。当我在 MyMachine 的上下文中犯了一个小错误时(更改context: { doc: { products: "a product" } }
, context: { doc: { product: "a product" } },
我确实看到了这个:
因此,承诺处理似乎有问题。我已经花了一天的时间;任何帮助表示赞赏!