【发布时间】:2020-06-20 14:16:15
【问题描述】:
我目前正在使用 Firebase 开发 HTTPS 云功能,包括删除我的 Android 用户请求的帖子。
总体思路
工作流程是(整个代码在这个 SO 问题的末尾可用):1)Firebase 检查用户身份(admin.auth().verifyIdToken); 2) Firestore 从帖子中获取必须删除的数据 (deleteDbEntry.get().then()) ; 3)云存储准备删除获取到的数据中的文件(.file(filePath).delete()); 4) Firestore 准备一批删除帖子 (batch.delete(deleteDbEntry);) 并使用获取的数据 (batch.update(updateUserLikes,) 更新喜欢/不喜欢的人; 5)执行删除文件和批处理的承诺(return Promise.all([deleteFile, batch_commit]))。
预期行为
我想检查用户身份。如果成功,则使用 Firebase 获取请求的帖子以删除数据。如果成功,我想在同一个承诺中执行 Firestore 批处理和 Cloud Storage 文件删除(这就是我使用 Promise.all([deleteFile, batch_commit]).then() 的原因)。如果身份检查失败,或者数据获取失败,或者批处理失败,我想告诉 Android 应用程序。如果一切顺利,同上。
由于所有这些操作都在 Cloud HTTPS 函数中,我必须返回一个承诺。我认为,如果这些操作成功,则该承诺将对应于所有操作,如果至少有一个操作不成功,则对应于错误(?)。
实际行为
目前,我只是返回 Firebase 用户身份检查的承诺。
我的问题和我的问题
我无法从实际行为转变为预期行为,因为:
我觉得在这个 Cloud HTTPS Function 中是否应该返回与“所有这些操作都成功,或者至少有一个不成功”对应的 Promise,我觉得不是很清楚
由于这些操作是嵌套的(Firestorage 文件删除 + Firestore 后删除批量存在),我无法返回类似
Promise.all()的内容。
我的问题
您能否告诉我我是否正确(第 1 点),如果不是:我该怎么办?如果是:由于第 2 点,我该怎么做?
整个 Firebase Cloud HTTPS 功能代码
注意:我删除了输入数据控件以使我的代码更清晰。
exports.deletePost = functions.https.onCall((data, context) => {
return admin.auth().verifyIdToken(idToken)
.then(function(decodedToken) {
const uid = decodedToken.uid;
const type_of_post = data.type_of_post;
const the_post = data.the_post;
const deleteDbEntry = admin_firestore.collection('list_of_' + type_of_post).doc(the_post);
const promise = deleteDbEntry.get().then(function(doc) {
const filePath = type_of_post + '/' + uid + '/' + data.stored_image_name;
const deleteFile = storage.bucket('android-f.appspot.com').file(filePath).delete();
const batch = admin.firestore().batch();
batch.delete(deleteDbEntry);
if(doc.data().number_of_likes > 0) {
const updateUserLikes = admin_firestore.collection("users").doc(uid);
batch.update(updateUserLikes, "likes", FieldValue.increment(-doc.data().number_of_likes));
}
const batch_commit = batch.commit();
return Promise.all([deleteFile, batch_commit]).then(function() {
return 1;
}).catch(function(error) {
console.log(error);
throw new functions.https.HttpsError('unknown', 'Unable to delete the post. (2)');
});
}).catch(function(error) {
console.log(error);
throw new functions.https.HttpsError('unknown', 'Unable to delete the post. (1)');
});
return promise;
}).catch(function(error) {
console.log(error);
throw new functions.https.HttpsError('unknown', 'An error occurred while verifying the token.');
});
});
【问题讨论】:
标签: javascript android firebase google-cloud-firestore google-cloud-functions