fix(challenges): better handling of deleted challenges. If !chal, break the task.challenge. Move the function into userController#score so we have access to next, etc. fixes #1883

This commit is contained in:
Tyler Renelle
2014-02-14 19:44:12 -07:00
parent 00bece28d4
commit 33b326b596
2 changed files with 19 additions and 19 deletions
+19 -3
View File
@@ -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();
});
});
};
/**
-16
View File
@@ -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;