如何解决如果Cloud Function无法执行,如何回滚?
我所做的是编写Cloud Function并依赖firebase admin SDK。
当前结果是有时云功能无法执行,只能创建新用户。我怀疑这是因为嵌套的诺言。
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.createuser = functions
.region("asia-southeast2")
.https.onCall((data,context) => {
if (!context.auth) {
throw new functions.https.HttpsError(
"Failed-precondition","The function must be called " + "while authenticated."
);
}
// question: how to combine promises?
return admin
.auth()
.createuser(data)
.then((user) => {
return admin
.firestore()
.collection("user")
.doc(user.uid)
.set({
access_rights: {
administration: data.administration,purchase: data.purchase,inventory: data.inventory,sales: data.sales,},name: data.displayName,email: data.email,street: data.street,city: data.city,zip: data.zip,phone: data.phone,})
.catch((error) => {
throw new functions.https.HttpsError(error.code,error.message);
});
})
.catch((error) => {
throw new functions.https.HttpsError(error.code,error.message);
});
});
解决方法
我写了一个简单的回滚,但是花了4秒才能完成。随时添加改进,我肯定会将其标记为答案。
这个想法很简单:一个onCall函数createUser
由前端调用,该函数还接收有效负载。
- 如果createUser进程失败,将引发错误。
- 如果createUser进程成功。它将称为
createDocument()
。createDocument()
可以在发生错误的情况下自行回调。
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
function createDocument({ user,data }) {
console.log("createDocument(),user.uid",user.uid,typeof user.uid);
admin
.firestore()
.collection("user")
.doc(user.uid)
.set({
access_rights: {
administration: data.administration,purchase: data.purchase,inventory: data.inventory,sales: data.sales,},name: data.displayName,email: data.email,street: data.street,city: data.city,zip: data.zip,phone: data.phone,})
.then(console.log("createDocument() DONE"))
.catch(() => {
console.log("createDocument() catch()");
return createDocument({ user,data });
});
}
exports.createUser = functions
.region("asia-southeast2")
.https.onCall((data,context) => {
if (!context.auth) {
throw new functions.https.HttpsError(
"failed-precondition","The function must be called " + "while authenticated."
);
}
return admin
.auth()
.createUser(data)
.then((response) => {
return createDocument({ user: response,data });
})
.catch((error) => {
throw new functions.https.HttpsError(error.code,error.message);
});
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。