【问题标题】:The Cloud function that returns a batch commit does not wait for that commit to make changes to the database before it completes返回批量提交的 Cloud 函数不会等待该提交在完成之前对数据库进行更改
【发布时间】:2020-07-30 18:45:01
【问题描述】:

在 Cloud Functions 中,我定义了一个函数,它使用我提交的批处理进行一些更新。这个提交是函数的返回。这个函数只是计算每个帖子的点赞数(点赞和帖子是我的 Firestore 数据库中的两个不同的集合)。由于整个代码很短而且很容易理解,所以我在下面展示一下。

喜欢或不喜欢帖子(从喜欢集合中添加或删除喜欢的文档)的事实是由应用程序在客户端完成的。 计算一些统计数据(例如每个帖子的点赞数)的事实在以下云函数中位于服务器端。 (因为如果它是客户端,它将是可破解的,即会生成并保存错误的统计信息+处理统计信息不直接涉及 Android 应用程序,因此它绝对应该在服务器端计算)。

需要注意的是:return batch.commit是这个Cloud Function的返回值。

exports.sortPostsByUsersPostsLikes = functions.https.onCall((data, context) => {
    if(!context.auth) {
        throw new functions.https.HttpsError('failed-precondition', 'The function must be called while authenticated.');
    }

    const batch = admin.firestore().batch();
    const posts = admin_firestore.collection('list_of_users_posts');
    const likes = admin_firestore.collection('likes_of_users_posts');
    const map_posts_id_with_number_of_likes = [];
    likes.get().then(function(likes_docs) {
        likes_docs.forEach(like_doc => {
            if(!(like_doc.data().post in map_posts_id_with_number_of_likes)) {
                map_posts_id_with_number_of_likes[like_doc.data().post] = 0;
            }
            map_posts_id_with_number_of_likes[like_doc.data().post] += 1;
        });       
        return posts.get();

    }).then(function(posts_docs) {
        posts_docs.forEach(post_doc => {
            if(post_doc.id in map_posts_id_with_number_of_likes) {
                        batch.update(post_doc.ref, "number_of_likes", map_posts_id_with_number_of_likes[post_doc.id]);
            } else {
                        batch.update(post_doc.ref, "number_of_likes", 0);
            }
        });     
        return batch.commit();

    }).catch(function(error) {
        console.log("UNABLE TO SORT THE POSTS");
        console.log(error);
        throw new functions.https.HttpsError('unknown', 'An error occurred when trying to sort the posts.');
    });

});

在我的 Android 应用中,当用户在帖子列表中点赞帖子时:

  1. 首先,我在likes 集合中添加了一个like
  2. 当赞成功添加到数据库的赞集合中后,我刷新帖子列表
  3. 当帖子列表显示(或刷新)时,我调用上面的云函数以重新计算帖子的点赞数(很快,“显示的帖子”)。
  4. 当帖子的点赞数成功重新计算后,我会显示帖子(因此每个显示的帖子的点赞数都是正确的)。

问题

问题是:在第 4 步,每个显示的帖子的点赞数不正确(有时正确,有时错误)。好像云函数没有等待批量提交结束。这是正常行为吗?有什么方法可以强制 Cloud Function 等待批处理的提交成功?

我在 Android 应用程序中使用的代码调用上述云函数,然后,如果成功,通常会显示帖子(通常有很多喜欢,但实际上并非如此)是:

        FirebaseFunctions.getInstance()
                .getHttpsCallable("sortPostsByUsersPostsLikes")
                .call()
                .continueWith(new Continuation<HttpsCallableResult, Void>() {
                    @Override
                    public Void then(@NonNull final Task<HttpsCallableResult> task) {
                        if(requireActivity().isDestroyed() || requireActivity().isFinishing()) {
                            return null;
                        }

                        if(!task.isSuccessful()) {
                            Exception e = task.getException();
                            if (e instanceof FirebaseFunctionsException) {
                                FirebaseFunctionsException ffe = (FirebaseFunctionsException) e;
                                if(ffe.getCode() == FirebaseFunctionsException.Code.UNKNOWN) {
                                    miscellaneous.showErrorPopIn(requireActivity(), R.string.error_sortPostsByUsersPostsLikes);
                                }
                            }
                            return null;
                        }

                        postsDatabaseModel.getListOfPostsOfUser(the_posts_owner).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

返回批量提交并添加then 不起作用

我尝试了以下方法,但它不起作用:

.then(function(posts_docs) {
        posts_docs.forEach(post_doc => {
            if(post_doc.id in map_posts_id_with_number_of_likes) {
                        batch.update(post_doc.ref, "number_of_likes", map_posts_id_with_number_of_likes[post_doc.id]);
            } else {
                        batch.update(post_doc.ref, "number_of_likes", 0);
            }
        });     
        return batch.commit();

    }).then(function() {
        return true;

    }).catch(function(error) {

【问题讨论】:

  • 对我来说,真正的问题是:你为什么要通过云函数来做简单的增量,在这种情况下,当你可以通过使用 FieldValue.increment(1) 直接在 Firestore 上的应用程序中执行此操作时?或递减FieldValue.increment(-1)
  • 安卓应用不需要更新所有帖子的like,它必须是服务器端的。顺便说一句,我无法验证 Android 应用程序是否会使用实际的点赞数而不是被黑的、错误的点赞数来更新点赞数。所以它肯定是一个云功能。
  • 但请注意,点赞或取消点赞,从赞集合中添加或删除赞,实际上是由 Android 应用程序在客户端完成的。
  • 考虑到在用户实际按下应用程序之前不会生成喜欢或不喜欢的事实,这意味着在文档 ea 中保留喜欢的数量。 likes: 50,在这种情况下,您希望保留ids 也喜欢帖子的用户,这使得简单的计算可​​以在本地解决。并不是说您的方法本身不起作用。但这取决于您如何在数据库中构建数据。
  • @Yupi 我实际上必须将喜欢存储在一个集合中(帖子ID,帖子所有者和喜欢的用户的ID),然后在集合中的每个帖子中都有一些喜欢计数器帖子数,计数器必须在服务器端更新:-)。

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


【解决方案1】:

您是正确的chaining 异步方法返回的承诺,但您没有返回整个链。你应该这样做:

exports.sortPostsByUsersPostsLikes = functions.https.onCall((data, context) => {
    if(!context.auth) {
        throw new functions.https.HttpsError('failed-precondition', 'The function must be called while authenticated.');
    }

    const batch = admin.firestore().batch();
    const posts = admin_firestore.collection('list_of_users_posts');
    const likes = admin_firestore.collection('likes_of_users_posts');
    const map_posts_id_with_number_of_likes = [];


    // SEE THE ADDITION OF RETURN BELOW
    return likes.get().then(function(likes_docs) {
        likes_docs.forEach(like_doc => {
            if(!(like_doc.data().post in map_posts_id_with_number_of_likes)) {
                map_posts_id_with_number_of_likes[like_doc.data().post] = 0;
            }
            map_posts_id_with_number_of_likes[like_doc.data().post] += 1;
        });       
        return posts.get();

    }).then(function(posts_docs) {
        posts_docs.forEach(post_doc => {
            if(post_doc.id in map_posts_id_with_number_of_likes) {
                        batch.update(post_doc.ref, "number_of_likes", map_posts_id_with_number_of_likes[post_doc.id]);
            } else {
                        batch.update(post_doc.ref, "number_of_likes", 0);
            }
        });     
        return batch.commit();

    }).catch(function(error) {
        console.log("UNABLE TO SORT THE POSTS");
        console.log(error);
        throw new functions.https.HttpsError('unknown', 'An error occurred when trying to sort the posts.');
    });
});

我建议您观看 Firebase 视频系列 (https://firebase.google.com/docs/functions/video-series/) 中有关“JavaScript Promises”的 3 个视频,这些视频强调了返回 Promise 的重要性。否则,Cloud Function 可能会在所有异步操作完成之前随时终止。


根据您的评论更新

如果您想记录 Cloud Function 成功的事实,您可以执行以下操作:

exports.sortPostsByUsersPostsLikes = functions.https.onCall((data, context) => {
    if(!context.auth) {
        throw new functions.https.HttpsError('failed-precondition', 'The function must be called while authenticated.');
    }

    //...

    return likes.get().then(function(likes_docs) {
        //...      
        return posts.get();

    }).then(function(posts_docs) {
        //...          
        return batch.commit();

    }).then(function() {
        console.log("SUCCESS")   
        return null;
    })
     .catch(function(error) {
        //...
    });

});

【讨论】:

  • 只是另一个问题:如果我考虑到您的回答并且如果我返回批处理提交并且如果我添加一个 then 在捕获之前/就在批处理提交之后返回 true,它会是更好的? (因为我最终会返回一个布尔值而不是一个 Promise) - 我会看你的视频,ty!
  • 添加“a then return true just before the catch/just after the batch commit”不会带来任何价值。添加then() 的唯一原因是在所有工作完成后记录一些内容,请参阅更新。 PS:这些不是“我的”视频,而是 Firebase 官方视频!! :-)
猜你喜欢
  • 1970-01-01
  • 2012-11-23
  • 1970-01-01
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多