diff --git a/src/controllers/user.js b/src/controllers/user.js index caaab30546..bd3011619e 100644 --- a/src/controllers/user.js +++ b/src/controllers/user.js @@ -89,10 +89,26 @@ api.score = function(req, res, next) { delta: delta, _tmp: user._tmp }, saved.toJSON().stats)); - }); - // if it's a challenge task, sync the score - user.syncScoreToChallenge(task, delta); + // If it's a challenge task, sync the score. Do it in the background, we've already sent down a response + // and the user doesn't care what happens back there + if (!task.challenge || !task.challenge.id || task.challenge.broken) return; + if (task.type == 'reward') return; // we don't want to update the reward GP cost + Challenge.findById(task.challenge.id, 'habits dailys todos rewards', function(err, chal){ + if (err) return next(err); + if (!chal) { + task.challenge.broken = 'CHALLENGE_DELETED'; + user.markModified('tasks'); + return user.save(); + } + var t = chal.tasks[task.id]; + if (!t) return chal.syncToUser(user); // this task was removed from the challenge, notify user + t.value += delta; + if (t.type == 'habit' || t.type == 'daily') + t.history.push({value: t.value, date: +new Date}); + chal.save(); + }); + }); }; /** diff --git a/src/models/user.js b/src/models/user.js index 93800629bf..9c1c5ba0cc 100644 --- a/src/models/user.js +++ b/src/models/user.js @@ -373,22 +373,6 @@ UserSchema.pre('save', function(next) { next(); }); -UserSchema.methods.syncScoreToChallenge = function(task, delta){ - if (!task.challenge || !task.challenge.id || task.challenge.broken) return; - if (task.type == 'reward') return; // we don't want to update the reward GP cost - var self = this; - Challenge.findById(task.challenge.id, function(err, chal){ - if (err) throw err; - var t = chal.tasks[task.id]; - if (!t) return chal.syncToUser(self); // this task was removed from the challenge, notify user - t.value += delta; - if (t.type == 'habit' || t.type == 'daily') { - t.history.push({value: t.value, date: +new Date}); - } - chal.save(); - }); -} - UserSchema.methods.unlink = function(options, cb) { var cid = options.cid, keep = options.keep, tid = options.tid; var self = this;