Created
January 28, 2016 03:26
-
-
Save vikdenic/a1f07fee9f319027923a to your computer and use it in GitHub Desktop.
Promises w/ Parse Cloud Code Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Parse.Cloud.beforeSave("Entry", function(request, response) { | |
| var entry = request.object; | |
| var contest = request.object.get("contest"); | |
| var fetchedUser, fetchedContest; | |
| var errorMessage; | |
| entry.get("user").fetch().then(function(result) { | |
| fetchedUser = result; | |
| return contest.fetch(); | |
| }).then(function(result) { | |
| fetchedContest = result; | |
| return fetchedContest.get("timeSlot").fetch(); | |
| }).then(function(fetchedTimeSlot) { | |
| // now we have all the variables we need to determine validity | |
| var now = new Date(); | |
| var hasSufficientFunds = fetchedUser.get("fundsAvailable") >= fetchedContest.get("entryFee"); | |
| var contestNotStarted = fetchedTimeSlot.get("startDate") >= now; | |
| if (hasSufficientFunds && contestNotStarted) { | |
| contest.increment("entriesCount"); | |
| contest.increment("entriesLimit", 0); //have to do this, otherwise entriesLimit is undefined in save callback (?) | |
| return contest.save(); | |
| } else { | |
| errorMessage = (hasSufficientFunds)? 'This contest has already started.' : 'Insufficient Funds.'; | |
| return null; | |
| } | |
| }).then(function(result) { | |
| if (!result) { | |
| response.error(errorMessage); | |
| } else { | |
| if (contest.get("entriesCount") > contest.get("entriesLimit")) { | |
| response.error('The contest is full.'); | |
| } else { | |
| response.success(); | |
| } | |
| } | |
| }, function(error) { | |
| response.error(error); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment