Thursday, 27 April 2017

Solve a transaction with mongodb (waterline.js) and node.js (sails.js)

Given is this situation:

-UserA publishs a Campaign with a given amount of photo uploads.

-other Users can upload Photos

-UserA can accept the uploaded Photos

-the owner of the photos get for each accepted photo 1 Coin

-for each accepted photo the amount of possible photos in the campaign decrease.

I solved the "accept photos" function like this (pseudocode):

accept: function (req, res, next) {

        var photos = req.param('photos'); // [1, 2, 5]
        var campaign_id = req.param('campaign_id'); //1

        Photo.update(photos, {status:'accepted'}).exec(function afterwards(err, updatedPhotos) 
            {
                     //get the users Ids from the updatedPhotos
                      // also know how many photos of each user were accepted

                      User.update(users){
                         //increase the amount of coins of this user 
                       }

                      Campaign.update(amountOfAcceptedPhotos){
                         //decrease the amount of selectable photos. 
                       }

            })

}

Everything worked well first, til I noticed when you send quickly the same request with the same photoID's, the Users will get for the same photo multiple coins! How can I prevent this?

Here is a Link for the whole Code, if you want to see the exact function: https://jsfiddle.net/zsmuoh0x/



via PomeGranate

No comments:

Post a Comment