A. Newbie
A. Newbie

Reputation: 187

Question about the correct use of transaction in a simple use case in a cloud function

I am trying to add +1 to a specific field in the realtime database. My function:

exports.dbWriteOnNewPost = functions.database.ref('/posts/{postid}').onWrite((change, context) => {
        const postUUID = context.params.postid;
        const postData = change.after.val();
        const communityUUID = postData.community;
        const authorUUID = postData.author;
        const postDate = postData.date;

        const promisePostByCommunity = admin.database().ref('/posts_by_community/' + communityUUID + '/' + postUUID).set(postDate);
        const promisePostByUser = admin.database().ref('/posts_by_user/' + authorUUID + '/' + postUUID).set(postDate);
        const promiseCommunityPostsCount = admin.database().ref('/communities/' + communityUUID + '/posts_count').transaction(
            (posts_value) => {
                return posts_value + 1;
            }
        );
        return Promise.all([promisePostByCommunity, promisePostByUser, promiseCommunityPostsCount]);
    });

I am simply asking if this transaction will prevent assigning wrong value, if for example 10 users are creating posts in the exact same time, which is going to happen if I use typical .once value => .set ?
EDIT: Finally managed to test it without breaking anything and the code above works perfectly fine.

Upvotes: 0

Views: 46

Answers (1)

gar.stauffer
gar.stauffer

Reputation: 157

I'm not too familiar with Firebase, but it looks like Transactions will do exactly what you want out of the box. The description for this seems to directly answer your question

The update function takes the current state of the data as an argument and returns the new desired state you would like to write. If another client writes to the location before your new value is successfully written, your update function is called again with the new current value, and the write is retried.

documentation: https://firebase.google.com/docs/database/web/read-and-write#save_data_as_transactions

Upvotes: 1

Related Questions