Cloud Function:如何让 likePost() 幂等?

问题描述 投票:0回答:0

我使用以下云功能:

exports.likePost = functions.https.onCall(async (data, context) => {

    // ...

    const db = admin.database();

    // check if post is already liked 
    const likeInteractionRef = db.ref(...); 
    const snapAlreadyLiked = await likeInteractionRef.once("value"); 
    const alreadyLiked = snapAlreadyLiked.exists();

    if (alreadyLiked) { 
        // remove the like 
        await likeInteractionRef.remove();

        // decrease post's like count await 
        likeCountRef.set(admin.database.ServerValue.increment(-1));

    } else { 
        // set as liked 
        await likeInteractionRef.set(true);

        // decrease post's like count 
        await likeCountRef.set(admin.database.ServerValue.increment(1));     
    }

    // return success 
    return { success: true }; 
});

有一个问题:它不是幂等的。如果该函数被同一用户无延迟地调用两次,它将转到 if-else-statement 的同一个分支,之后 like-count 将不正确。

我该如何解决这个问题?

javascript firebase google-cloud-platform google-cloud-functions firebase-admin
© www.soinside.com 2019 - 2024. All rights reserved.