finish porting to async/away syntax

This commit is contained in:
Matteo Pagliazzi
2015-12-31 11:46:21 +01:00
parent f76c9d025f
commit aebe2fa400
7 changed files with 560 additions and 652 deletions

View File

@@ -56,7 +56,7 @@ api.registerLocal = {
let lowerCaseUsername = username.toLowerCase(); let lowerCaseUsername = username.toLowerCase();
// Search for duplicates using lowercase version of username // Search for duplicates using lowercase version of username
let user = User.findOne({$or: [ let user = await User.findOne({$or: [
{'auth.local.email': email}, {'auth.local.email': email},
{'auth.local.lowerCaseUsername': lowerCaseUsername}, {'auth.local.lowerCaseUsername': lowerCaseUsername},
]}, {'auth.local': 1}).exec(); ]}, {'auth.local': 1}).exec();

View File

@@ -27,75 +27,72 @@ api.createChallenge = {
method: 'POST', method: 'POST',
url: '/challenges', url: '/challenges',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkBody('group', res.t('groupIdRequired')).notEmpty(); req.checkBody('group', res.t('groupIdRequired')).notEmpty();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
let groupId = req.body.group; let groupId = req.body.group;
let prize = req.body.prize; let prize = req.body.prize;
Group.getGroup(user, groupId, '-chat') let group = await Group.getGroup(user, groupId, '-chat');
.then(group => { if (!group) throw new NotFound(res.t('groupNotFound'));
if (!group) throw new NotFound(res.t('groupNotFound'));
if (group.leaderOnly && group.leaderOnly.challenges && group.leader !== user._id) { if (group.leaderOnly && group.leaderOnly.challenges && group.leader !== user._id) {
throw new NotAuthorized(res.t('onlyGroupLeaderChal')); throw new NotAuthorized(res.t('onlyGroupLeaderChal'));
}
if (groupId === 'habitrpg' && prize < 1) {
throw new NotAuthorized(res.t('pubChalsMinPrize'));
}
if (prize > 0) {
let groupBalance = group.balance && group.leader === user._id ? group.balance : 0;
let prizeCost = prize / 4;
if (prizeCost > user.balance + groupBalance) {
throw new NotAuthorized(res.t('cantAfford'));
} }
if (groupId === 'habitrpg' && prize < 1) { if (groupBalance >= prizeCost) {
throw new NotAuthorized(res.t('pubChalsMinPrize')); // Group pays for all of prize
group.balance -= prizeCost;
} else if (groupBalance > 0) {
// User pays remainder of prize cost after group
let remainder = prizeCost - group.balance;
group.balance = 0;
user.balance -= remainder;
} else {
// User pays for all of prize
user.balance -= prizeCost;
} }
}
if (prize > 0) { group.challengeCount += 1;
let groupBalance = group.balance && group.leader === user._id ? group.balance : 0;
let prizeCost = prize / 4;
if (prizeCost > user.balance + groupBalance) { let tasks = req.body.tasks || []; // TODO validate
throw new NotAuthorized(res.t('cantAfford')); req.body.leader = user._id;
} req.body.official = user.contributor.admin && req.body.official;
let challenge = new Challenge(Challenge.sanitize(req.body));
if (groupBalance >= prizeCost) { let toSave = tasks.map(tasks, taskToCreate => {
// Group pays for all of prize // TODO validate type
group.balance -= prizeCost; let task = new Tasks[taskToCreate.type](Tasks.Task.sanitizeCreate(taskToCreate));
} else if (groupBalance > 0) { task.challenge.id = challenge._id;
// User pays remainder of prize cost after group challenge.tasksOrder[`${task.type}s`].push(task._id);
let remainder = prizeCost - group.balance; return task.save();
group.balance = 0; });
user.balance -= remainder;
} else {
// User pays for all of prize
user.balance -= prizeCost;
}
}
group.challengeCount += 1; toSave.unshift(challenge, group);
let tasks = req.body.tasks || []; // TODO validate let results = await Q.all(toSave);
req.body.leader = user._id; let savedChal = results[0];
req.body.official = user.contributor.admin && req.body.official;
let challenge = new Challenge(Challenge.sanitize(req.body));
let toSave = tasks.map(tasks, taskToCreate => { await savedChal.syncToUser(user); // (it also saves the user)
// TODO validate type res.respond(201, savedChal);
let task = new Tasks[taskToCreate.type](Tasks.Task.sanitizeCreate(taskToCreate));
task.challenge.id = challenge._id;
challenge.tasksOrder[`${task.type}s`].push(task._id);
return task.save();
});
toSave.unshift(challenge, group);
return Q.all(toSave);
})
.then(results => {
let savedChal = results[0];
return savedChal.syncToUser(user) // (it also saves the user)
.then(() => res.respond(201, savedChal));
})
.catch(next);
}, },
}; };
@@ -111,14 +108,14 @@ api.getChallenges = {
method: 'GET', method: 'GET',
url: '/challenges', url: '/challenges',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
let groups = user.guilds || []; let groups = user.guilds || [];
if (user.party._id) groups.push(user.party._id); if (user.party._id) groups.push(user.party._id);
groups.push('habitrpg'); // Public challenges groups.push('habitrpg'); // Public challenges
Challenge.find({ let challenges = await Challenge.find({
$or: [ $or: [
{_id: {$in: user.challenges}}, // Challenges where the user is participating {_id: {$in: user.challenges}}, // Challenges where the user is participating
{group: {$in: groups}}, // Challenges in groups where I'm a member {group: {$in: groups}}, // Challenges in groups where I'm a member
@@ -130,11 +127,9 @@ api.getChallenges = {
// TODO populate // TODO populate
// .populate('group', '_id name type') // .populate('group', '_id name type')
// .populate('leader', 'profile.name') // .populate('leader', 'profile.name')
.exec() .exec();
.then(challenges => {
res.respond(200, challenges); res.respond(200, challenges);
})
.catch(next);
}, },
}; };
@@ -190,7 +185,7 @@ function _closeChal (challenge, broken = {}) {
})); }));
} }
return Q.allSettled(tasks); // TODO look if allSettle could be useful somewhere else return Q.allSettled(tasks); // TODO look if allSettled could be useful somewhere else
// TODO catch and handle // TODO catch and handle
} }
@@ -206,25 +201,21 @@ api.deleteChallenge = {
method: 'DELETE', method: 'DELETE',
url: '/challenges/:challengeId', url: '/challenges/:challengeId',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkParams('challenge', res.t('challengeIdRequired')).notEmpty().isUUID(); req.checkParams('challenge', res.t('challengeIdRequired')).notEmpty().isUUID();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Challenge.findOne({_id: req.params.challengeId}) let challenge = await Challenge.findOne({_id: req.params.challengeId}).exec();
.exec() if (!challenge) throw new NotFound(res.t('challengeNotFound'));
.then(challenge => { if (challenge.leader !== user._id && !user.contributor.admin) throw new NotAuthorized(res.t('onlyLeaderDeleteChal'));
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
if (challenge.leader !== user._id && !user.contributor.admin) throw new NotAuthorized(res.t('onlyLeaderDeleteChal'));
res.respond(200, {}); res.respond(200, {});
// Close channel in background // Close channel in background
_closeChal(challenge, {broken: 'CHALLENGE_DELETED'}); _closeChal(challenge, {broken: 'CHALLENGE_DELETED'});
})
.catch(next);
}, },
}; };
@@ -240,34 +231,25 @@ api.selectChallengeWinner = {
method: 'POST', method: 'POST',
url: '/challenges/:challengeId/selectWinner/:winnerId', url: '/challenges/:challengeId/selectWinner/:winnerId',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
let challenge;
req.checkParams('challenge', res.t('challengeIdRequired')).notEmpty().isUUID(); req.checkParams('challenge', res.t('challengeIdRequired')).notEmpty().isUUID();
req.checkParams('winnerId', res.t('winnerIdRequired')).notEmpty().isUUID(); req.checkParams('winnerId', res.t('winnerIdRequired')).notEmpty().isUUID();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Challenge.findOne({_id: req.params.challengeId}) let challenge = await Challenge.findOne({_id: req.params.challengeId}).exec();
.exec() if (!challenge) throw new NotFound(res.t('challengeNotFound'));
.then(challengeFound => { if (challenge.leader !== user._id && !user.contributor.admin) throw new NotAuthorized(res.t('onlyLeaderDeleteChal'));
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
if (challenge.leader !== user._id && !user.contributor.admin) throw new NotAuthorized(res.t('onlyLeaderDeleteChal'));
challenge = challengeFound; let winner = await User.findOne({_id: req.params.winnerId}).exec();
if (!winner || winner.challenges.indexOf(challenge._id) === -1) throw new NotFound(res.t('winnerNotFound', {userId: req.parama.winnerId}));
return User.findOne({_id: req.params.winnerId}).exec(); res.respond(200, {});
}) // Close channel in background
.then(winner => { _closeChal(challenge, {broken: 'CHALLENGE_DELETED', winner});
if (!winner || winner.challenges.indexOf(challenge._id) === -1) throw new NotFound(res.t('winnerNotFound', {userId: req.parama.winnerId}));
res.respond(200, {});
// Close channel in background
_closeChal(challenge, {broken: 'CHALLENGE_DELETED', winner});
})
.catch(next);
}, },
}; };

View File

@@ -25,21 +25,18 @@ api.getChat = {
method: 'GET', method: 'GET',
url: '/groups/:groupId/chat', url: '/groups/:groupId/chat',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty(); req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Group.getGroup(user, req.params.groupId, 'chat') let group = await Group.getGroup(user, req.params.groupId, 'chat');
.then(group => { if (!group) throw new NotFound(res.t('groupNotFound'));
if (!group) throw new NotFound(res.t('groupNotFound'));
res.respond(200, group.chat); res.respond(200, group.chat);
})
.catch(next);
}, },
}; };
@@ -59,7 +56,7 @@ api.postChat = {
method: 'POST', method: 'POST',
url: '/groups/:groupId/chat', url: '/groups/:groupId/chat',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
let groupId = req.params.groupId; let groupId = req.params.groupId;
let chatUpdated; let chatUpdated;
@@ -68,34 +65,31 @@ api.postChat = {
req.checkBody('message', res.t('messageGroupChatBlankMessage')).notEmpty(); req.checkBody('message', res.t('messageGroupChatBlankMessage')).notEmpty();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Group.getGroup(user, groupId) let group = await Group.getGroup(user, groupId);
.then((group) => {
if (!group) throw new NotFound(res.t('groupNotFound'));
if (group.type !== 'party' && user.flags.chatRevoked) {
throw new NotFound('Your chat privileges have been revoked.');
}
let lastClientMsg = req.query.previousMsg; if (!group) throw new NotFound(res.t('groupNotFound'));
chatUpdated = lastClientMsg && group.chat && group.chat[0] && group.chat[0].id !== lastClientMsg ? true : false; if (group.type !== 'party' && user.flags.chatRevoked) {
throw new NotFound('Your chat privileges have been revoked.');
}
group.sendChat(req.body.message, user); let lastClientMsg = req.query.previousMsg;
chatUpdated = lastClientMsg && group.chat && group.chat[0] && group.chat[0].id !== lastClientMsg ? true : false;
if (group.type === 'party') { group.sendChat(req.body.message, user);
user.party.lastMessageSeen = group.chat[0].id;
user.save(); if (group.type === 'party') {
} user.party.lastMessageSeen = group.chat[0].id;
return group.save(); user.save(); // TODO why this is non-blocking? must catch?
}) }
.then((group) => {
if (chatUpdated) { let savedGroup = await group.save();
res.respond(200, {chat: group.chat}); if (chatUpdated) {
} else { res.respond(200, {chat: savedGroup.chat});
res.respond(200, {message: group.chat[0]}); } else {
} res.respond(200, {message: savedGroup.chat[0]});
}) }
.catch(next);
}, },
}; };
@@ -114,42 +108,35 @@ api.likeChat = {
method: 'Post', method: 'Post',
url: '/groups/:groupId/chat/:chatId/like', url: '/groups/:groupId/chat/:chatId/like',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
let groupId = req.params.groupId; let groupId = req.params.groupId;
let message;
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty(); req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
req.checkParams('chatId', res.t('chatIdRequired')).notEmpty(); req.checkParams('chatId', res.t('chatIdRequired')).notEmpty();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Group.getGroup(user, groupId) let group = await Group.getGroup(user, groupId);
.then((group) => { if (!group) throw new NotFound(res.t('groupNotFound'));
if (!group) throw new NotFound(res.t('groupNotFound'));
message = _.find(group.chat, {id: req.params.chatId});
if (!message) throw new NotFound(res.t('messageGroupChatNotFound'));
if (message.uuid === user._id) throw new NotFound(res.t('messageGroupChatLikeOwnMessage')); let message = _.find(group.chat, {id: req.params.chatId});
if (!message) throw new NotFound(res.t('messageGroupChatNotFound'));
if (message.uuid === user._id) throw new NotFound(res.t('messageGroupChatLikeOwnMessage'));
let update = {$set: {}}; let update = {$set: {}};
if (!message.likes) message.likes = {}; if (!message.likes) message.likes = {};
message.likes[user._id] = !message.likes[user._id]; message.likes[user._id] = !message.likes[user._id];
update.$set[`chat.$.likes.${user._id}`] = message.likes[user._id]; update.$set[`chat.$.likes.${user._id}`] = message.likes[user._id];
return Group.update( await Group.update(
{_id: group._id, 'chat.id': message.id}, {_id: group._id, 'chat.id': message.id},
update update
); );
}) res.respond(200, message);
.then((groupSaved) => {
if (!groupSaved) throw new NotFound(res.t('groupNotFound'));
res.respond(200, message);
})
.catch(next);
}, },
}; };
@@ -168,116 +155,104 @@ api.flagChat = {
method: 'Post', method: 'Post',
url: '/groups/:groupId/chat/:chatId/flag', url: '/groups/:groupId/chat/:chatId/flag',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
let groupId = req.params.groupId; let groupId = req.params.groupId;
let message;
let group;
let author;
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty(); req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
req.checkParams('chatId', res.t('chatIdRequired')).notEmpty(); req.checkParams('chatId', res.t('chatIdRequired')).notEmpty();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Group.getGroup(user, groupId) let group = await Group.getGroup(user, groupId);
.then((groupFound) => { if (!group) throw new NotFound(res.t('groupNotFound'));
if (!groupFound) throw new NotFound(res.t('groupNotFound')); let message = _.find(group.chat, {id: req.params.chatId});
group = groupFound;
message = _.find(group.chat, {id: req.params.chatId});
if (!message) throw new NotFound(res.t('messageGroupChatNotFound')); if (!message) throw new NotFound(res.t('messageGroupChatNotFound'));
if (message.uuid === user._id) throw new NotFound(res.t('messageGroupChatFlagOwnMessage')); if (message.uuid === user._id) throw new NotFound(res.t('messageGroupChatFlagOwnMessage'));
return User.findOne({_id: message.uuid}, {auth: 1}); let author = await User.findOne({_id: message.uuid}, {auth: 1});
})
.then((foundAuthor) => {
author = foundAuthor;
let update = {$set: {}}; let update = {$set: {}};
// Log user ids that have flagged the message // Log user ids that have flagged the message
if (!message.flags) message.flags = {}; if (!message.flags) message.flags = {};
if (message.flags[user._id] && !user.contributor.admin) throw new NotFound(res.t('messageGroupChatFlagAlreadyReported')); if (message.flags[user._id] && !user.contributor.admin) throw new NotFound(res.t('messageGroupChatFlagAlreadyReported'));
message.flags[user._id] = true; message.flags[user._id] = true;
update.$set[`chat.$.flags.${user._id}`] = true; update.$set[`chat.$.flags.${user._id}`] = true;
// Log total number of flags (publicly viewable) // Log total number of flags (publicly viewable)
if (!message.flagCount) message.flagCount = 0; if (!message.flagCount) message.flagCount = 0;
if (user.contributor.admin) { if (user.contributor.admin) {
// Arbitraty amount, higher than 2 // Arbitraty amount, higher than 2
message.flagCount = 5; message.flagCount = 5;
} else { } else {
message.flagCount++; message.flagCount++;
} }
update.$set['chat.$.flagCount'] = message.flagCount; update.$set['chat.$.flagCount'] = message.flagCount;
return Group.update( await Group.update(
{_id: group._id, 'chat.id': message.id}, {_id: group._id, 'chat.id': message.id},
update update
); );
})
.then((group2) => {
if (!group2) throw new NotFound(res.t('groupNotFound'));
let addressesToSendTo = nconf.get('FLAG_REPORT_EMAIL'); let addressesToSendTo = nconf.get('FLAG_REPORT_EMAIL');
addressesToSendTo = typeof addressesToSendTo === 'string' ? JSON.parse(addressesToSendTo) : addressesToSendTo; addressesToSendTo = typeof addressesToSendTo === 'string' ? JSON.parse(addressesToSendTo) : addressesToSendTo;
if (Array.isArray(addressesToSendTo)) { if (Array.isArray(addressesToSendTo)) {
addressesToSendTo = addressesToSendTo.map((email) => { addressesToSendTo = addressesToSendTo.map((email) => {
return {email, canSend: true}; return {email, canSend: true};
}); });
} else { } else {
addressesToSendTo = {email: addressesToSendTo}; addressesToSendTo = {email: addressesToSendTo};
} }
let reporterEmailContent; let reporterEmailContent;
if (user.auth.local) { if (user.auth.local) {
reporterEmailContent = user.auth.local.email; reporterEmailContent = user.auth.local.email;
} else if (user.auth.facebook && user.auth.facebook.emails && user.auth.facebook.emails[0]) { } else if (user.auth.facebook && user.auth.facebook.emails && user.auth.facebook.emails[0]) {
reporterEmailContent = user.auth.facebook.emails[0].value; reporterEmailContent = user.auth.facebook.emails[0].value;
} }
let authorEmailContent; let authorEmailContent;
if (author.auth.local) { if (author.auth.local) {
authorEmailContent = author.auth.local.email; authorEmailContent = author.auth.local.email;
} else if (author.auth.facebook && author.auth.facebook.emails && author.auth.facebook.emails[0]) { } else if (author.auth.facebook && author.auth.facebook.emails && author.auth.facebook.emails[0]) {
authorEmailContent = author.auth.facebook.emails[0].value; authorEmailContent = author.auth.facebook.emails[0].value;
} }
let groupUrl; let groupUrl;
if (group._id === 'habitrpg') { if (group._id === 'habitrpg') {
groupUrl = '/#/options/groups/tavern'; groupUrl = '/#/options/groups/tavern';
} else if (group.type === 'guild') { } else if (group.type === 'guild') {
groupUrl = `/#/options/groups/guilds/{$group._id}`; groupUrl = `/#/options/groups/guilds/{$group._id}`;
} else { } else {
groupUrl = 'party'; groupUrl = 'party';
} }
sendTxn(addressesToSendTo, 'flag-report-to-mods', [ sendTxn(addressesToSendTo, 'flag-report-to-mods', [
{name: 'MESSAGE_TIME', content: (new Date(message.timestamp)).toString()}, {name: 'MESSAGE_TIME', content: (new Date(message.timestamp)).toString()},
{name: 'MESSAGE_TEXT', content: message.text}, {name: 'MESSAGE_TEXT', content: message.text},
{name: 'REPORTER_USERNAME', content: user.profile.name}, {name: 'REPORTER_USERNAME', content: user.profile.name},
{name: 'REPORTER_UUID', content: user._id}, {name: 'REPORTER_UUID', content: user._id},
{name: 'REPORTER_EMAIL', content: reporterEmailContent}, {name: 'REPORTER_EMAIL', content: reporterEmailContent},
{name: 'REPORTER_MODAL_URL', content: `/static/front/#?memberId={$user._id}`}, {name: 'REPORTER_MODAL_URL', content: `/static/front/#?memberId={$user._id}`},
{name: 'AUTHOR_USERNAME', content: message.user}, {name: 'AUTHOR_USERNAME', content: message.user},
{name: 'AUTHOR_UUID', content: message.uuid}, {name: 'AUTHOR_UUID', content: message.uuid},
{name: 'AUTHOR_EMAIL', content: authorEmailContent}, {name: 'AUTHOR_EMAIL', content: authorEmailContent},
{name: 'AUTHOR_MODAL_URL', content: `/static/front/#?memberId={$message.uuid}`}, {name: 'AUTHOR_MODAL_URL', content: `/static/front/#?memberId={$message.uuid}`},
{name: 'GROUP_NAME', content: group.name}, {name: 'GROUP_NAME', content: group.name},
{name: 'GROUP_TYPE', content: group.type}, {name: 'GROUP_TYPE', content: group.type},
{name: 'GROUP_ID', content: group._id}, {name: 'GROUP_ID', content: group._id},
{name: 'GROUP_URL', content: groupUrl}, {name: 'GROUP_URL', content: groupUrl},
]); ]);
res.respond(200, message);
}) res.respond(200, message);
.catch(next);
}, },
}; };

View File

@@ -29,36 +29,31 @@ api.createGroup = {
method: 'POST', method: 'POST',
url: '/groups', url: '/groups',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
let group = new Group(Group.sanitize(req.body)); // TODO validate empty req.body let group = new Group(Group.sanitize(req.body)); // TODO validate empty req.body
group.leader = user._id; group.leader = user._id;
if (group.type === 'guild') { if (group.type === 'guild') {
if (user.balance < 1) return next(new NotAuthorized(res.t('messageInsufficientGems'))); if (user.balance < 1) throw new NotAuthorized(res.t('messageInsufficientGems'));
group.balance = 1; group.balance = 1;
user.balance--; user.balance--;
user.guilds.push(group._id); user.guilds.push(group._id);
} else { } else {
if (user.party._id) return next(new NotAuthorized(res.t('messageGroupAlreadyInParty'))); if (user.party._id) throw new NotAuthorized(res.t('messageGroupAlreadyInParty'));
user.party._id = group._id; user.party._id = group._id;
} }
Q.all([ let results = await Q.all([user.save(), group.save()]);
user.save(), let savedGroup = results[1];
group.save(),
]).then(results => {
let savedGroup = results[1];
firebase.updateGroupData(savedGroup); firebase.updateGroupData(savedGroup);
firebase.addUserToGroup(savedGroup._id, user._id); firebase.addUserToGroup(savedGroup._id, user._id);
return res.respond(201, savedGroup); // TODO populate return res.respond(201, savedGroup); // TODO populate
})
.catch(next);
}, },
}; };
@@ -76,13 +71,13 @@ api.getGroups = {
method: 'GET', method: 'GET',
url: '/groups', url: '/groups',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkQuery('type', res.t('groupTypesRequired')).notEmpty(); // TODO better validation req.checkQuery('type', res.t('groupTypesRequired')).notEmpty(); // TODO better validation
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
// TODO validate types are acceptable? probably not necessary // TODO validate types are acceptable? probably not necessary
let types = req.query.type.split(','); let types = req.query.type.split(',');
@@ -115,16 +110,14 @@ api.getGroups = {
}); });
// If no valid value for type was supplied, return an error // If no valid value for type was supplied, return an error
if (queries.length === 0) return next(new BadRequest(res.t('groupTypesRequired'))); if (queries.length === 0) throw new BadRequest(res.t('groupTypesRequired'));
Q.all(queries) // TODO we would like not to return a single big array but Q doesn't support the funtionality https://github.com/kriskowal/q/issues/328 let results = await Q.all(queries); // TODO we would like not to return a single big array but Q doesn't support the funtionality https://github.com/kriskowal/q/issues/328
.then(results => {
res.respond(200, _.reduce(results, (m, v) => { res.respond(200, _.reduce(results, (m, v) => {
if (_.isEmpty(v)) return m; if (_.isEmpty(v)) return m;
return m.concat(Array.isArray(v) ? v : [v]); return m.concat(Array.isArray(v) ? v : [v]);
}, [])); }, []));
})
.catch(next);
}, },
}; };
@@ -142,21 +135,18 @@ api.getGroup = {
method: 'GET', method: 'GET',
url: '/groups/:groupId', url: '/groups/:groupId',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty(); req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Group.getGroup(user, req.params.groupId) let group = await Group.getGroup(user, req.params.groupId);
.then(group => { if (!group) throw new NotFound(res.t('groupNotFound'));
if (!group) throw new NotFound(res.t('groupNotFound'));
res.respond(200, group); res.respond(200, group);
})
.catch(next);
}, },
}; };
@@ -174,28 +164,24 @@ api.updateGroup = {
method: 'PUT', method: 'PUT',
url: '/groups/:groupId', url: '/groups/:groupId',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty(); req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Group.getGroup(user, req.params.groupId) let group = await Group.getGroup(user, req.params.groupId);
.then(group => { if (!group) throw new NotFound(res.t('groupNotFound'));
if (!group) throw new NotFound(res.t('groupNotFound'));
if (group.leader !== user._id) throw new NotAuthorized(res.t('messageGroupOnlyLeaderCanUpdate')); if (group.leader !== user._id) throw new NotAuthorized(res.t('messageGroupOnlyLeaderCanUpdate'));
_.assign(group, _.merge(group.toObject(), Group.sanitizeUpdate(req.body))); _.assign(group, _.merge(group.toObject(), Group.sanitizeUpdate(req.body)));
return group.save(); let savedGroup = await group.save();
}).then(savedGroup => { res.respond(200, savedGroup);
res.respond(200, savedGroup); firebase.updateGroupData(savedGroup);
firebase.updateGroupData(savedGroup);
})
.catch(next);
}, },
}; };
@@ -213,60 +199,57 @@ api.joinGroup = {
method: 'POST', method: 'POST',
url: '/groups/:groupId/join', url: '/groups/:groupId/join',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty().isUUID(); req.checkParams('groupId', res.t('groupIdRequired')).notEmpty().isUUID();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Group.getGroup(user, req.params.groupId, '-chat', true) // Do not fetch chat and work even if the user is not yet a member of the group let group = await Group.getGroup(user, req.params.groupId, '-chat', true); // Do not fetch chat and work even if the user is not yet a member of the group
.then(group => { if (!group) throw new NotFound(res.t('groupNotFound'));
if (!group) throw new NotFound(res.t('groupNotFound'));
let isUserInvited = false; let isUserInvited = false;
if (group.type === 'party' && group._id === (user.invitations.party && user.invitations.party.id)) { if (group.type === 'party' && group._id === (user.invitations.party && user.invitations.party.id)) {
user.invitations.party = {}; // Clear invite TODO mark modified? user.invitations.party = {}; // Clear invite TODO mark modified?
// invite new user to pending quest // invite new user to pending quest
if (group.quest.key && !group.quest.active) { if (group.quest.key && !group.quest.active) {
user.party.quest.RSVPNeeded = true; user.party.quest.RSVPNeeded = true;
user.party.quest.key = group.quest.key; user.party.quest.key = group.quest.key;
group.quest.members[user._id] = undefined; group.quest.members[user._id] = undefined;
group.markModified('quest.members'); group.markModified('quest.members');
}
user.party._id = group._id; // Set group as user's party
isUserInvited = true;
} else if (group.type === 'guild' && user.invitations.guilds) {
let i = _.findIndex(user.invitations.guilds, {id: group._id});
if (i !== -1) {
isUserInvited = true;
user.invitations.guilds.splice(i, 1); // Remove invitation
} else {
isUserInvited = group.privacy === 'private' ? false : true;
}
} }
if (isUserInvited && group.type === 'guild') user.guilds.push(group._id); // Add group to user's guilds user.party._id = group._id; // Set group as user's party
if (!isUserInvited) throw new NotAuthorized(res.t('messageGroupRequiresInvite'));
if (group.memberCount === 0) group.leader = user._id; // If new user is only member -> set as leader isUserInvited = true;
} else if (group.type === 'guild' && user.invitations.guilds) {
let i = _.findIndex(user.invitations.guilds, {id: group._id});
Q.all([ if (i !== -1) {
group.save(), isUserInvited = true;
user.save(), user.invitations.guilds.splice(i, 1); // Remove invitation
User.update({_id: user.invitations.party.inviter}, {$inc: {'items.quests.basilist': 1}}).exec(), // Reward inviter } else {
]).then(() => { isUserInvited = group.privacy === 'private' ? false : true;
firebase.addUserToGroup(group._id, user._id); }
res.respond(200, {}); // TODO what to return? }
});
}) if (isUserInvited && group.type === 'guild') user.guilds.push(group._id); // Add group to user's guilds
.catch(next); if (!isUserInvited) throw new NotAuthorized(res.t('messageGroupRequiresInvite'));
if (group.memberCount === 0) group.leader = user._id; // If new user is only member -> set as leader
await Q.all([
group.save(),
user.save(),
User.update({_id: user.invitations.party.inviter}, {$inc: {'items.quests.basilist': 1}}).exec(), // Reward inviter
]);
firebase.addUserToGroup(group._id, user._id);
res.respond(200, {}); // TODO what to return?
}, },
}; };
@@ -285,7 +268,7 @@ api.leaveGroup = {
method: 'POST', method: 'POST',
url: '/groups/:groupId/leave', url: '/groups/:groupId/leave',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty(); req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
@@ -293,27 +276,24 @@ api.leaveGroup = {
req.checkQuery('keep', res.t('keepOrRemoveAll')).optional().isIn(['keep-all', 'remove-all']); req.checkQuery('keep', res.t('keepOrRemoveAll')).optional().isIn(['keep-all', 'remove-all']);
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Group.getGroup(user, req.params.groupId, '-chat') // Do not fetch chat let group = await Group.getGroup(user, req.params.groupId, '-chat'); // Do not fetch chat
.then(group => { if (!group) throw new NotFound(res.t('groupNotFound'));
if (!group) throw new NotFound(res.t('groupNotFound'));
// During quests, checke wheter user can leave // During quests, checke wheter user can leave
if (group.type === 'party') { if (group.type === 'party') {
if (group.quest && group.quest.leader === user._id) { if (group.quest && group.quest.leader === user._id) {
throw new NotAuthorized(res.t('questLeaderCannotLeaveGroup')); throw new NotAuthorized(res.t('questLeaderCannotLeaveGroup'));
}
if (group.quest && group.quest.active && group.quest.members && group.quest.members[user._id]) {
throw new NotAuthorized(res.t('cannotLeaveWhileActiveQuest'));
}
} }
return group.leave(user, req.query.keep); if (group.quest && group.quest.active && group.quest.members && group.quest.members[user._id]) {
}) throw new NotAuthorized(res.t('cannotLeaveWhileActiveQuest'));
.then(() => res.respond(200, {})) }
.catch(next); }
await group.leave(user, req.query.keep);
res.respond(200, {});
}, },
}; };
@@ -345,71 +325,65 @@ api.removeGroupMember = {
method: 'POST', method: 'POST',
url: '/groups/:groupId/removeMember/:memberId', url: '/groups/:groupId/removeMember/:memberId',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
let group;
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty(); req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
req.checkParams('memberId', res.t('userIdRequired')).notEmpty().isUUID(); req.checkParams('memberId', res.t('userIdRequired')).notEmpty().isUUID();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Group.getGroup(user, req.params.groupId, '-chat') // Do not fetch chat let group = await Group.getGroup(user, req.params.groupId, '-chat'); // Do not fetch chat
.then(foundGroup => { if (!group) throw new NotFound(res.t('groupNotFound'));
group = foundGroup;
if (!group) throw new NotFound(res.t('groupNotFound'));
let uuid = req.query.memberId; let uuid = req.query.memberId;
if (group.leader !== user._id) throw new NotAuthorized(res.t('onlyLeaderCanRemoveMember')); if (group.leader !== user._id) throw new NotAuthorized(res.t('onlyLeaderCanRemoveMember'));
if (user._id === uuid) throw new NotAuthorized(res.t('memberCannotRemoveYourself')); if (user._id === uuid) throw new NotAuthorized(res.t('memberCannotRemoveYourself'));
return User.findOne({_id: uuid}).select('party guilds invitations newMessages').exec(); let member = await User.findOne({_id: uuid}).select('party guilds invitations newMessages').exec();
}).then(member => { // We're removing the user from a guild or a party? is the user invited only?
// We're removing the user from a guild or a party? is the user invited only? let isInGroup = member.party._id === group._id ? 'party' : member.guilds.indexOf(group._id) !== 1 ? 'guild' : undefined; // eslint-disable-line no-nested-ternary
let isInGroup = member.party._id === group._id ? 'party' : member.guilds.indexOf(group._id) !== 1 ? 'guild' : undefined; // eslint-disable-line no-nested-ternary let isInvited = member.invitations.party.id === group._id ? 'party' : _.findIndex(member.invitations.guilds, {id: group._id}) !== 1 ? 'guild' : undefined; // eslint-disable-line no-nested-ternary
let isInvited = member.invitations.party.id === group._id ? 'party' : _.findIndex(member.invitations.guilds, {id: group._id}) !== 1 ? 'guild' : undefined; // eslint-disable-line no-nested-ternary
if (isInGroup) { if (isInGroup) {
group.memberCount -= 1; group.memberCount -= 1;
if (group.quest && group.quest.leader === member._id) { if (group.quest && group.quest.leader === member._id) {
group.quest.key = null; group.quest.key = null;
group.quest.leader = null; // TODO markmodified? group.quest.leader = null; // TODO markmodified?
} else if (group.quest && group.quest.members) { } else if (group.quest && group.quest.members) {
// remove member from quest // remove member from quest
group.quest.members[member._id] = undefined; group.quest.members[member._id] = undefined;
}
if (isInGroup === 'guild') _.pull(member.guilds, group._id);
if (isInGroup === 'party') member.party._id = undefined; // TODO remove quest information too?
member.newMessages.group._id = undefined;
if (group.quest && group.quest.active && group.quest.leader === member._id) {
member.items.quests[group.quest.key] += 1; // TODO why this?
}
} else if (isInvited) {
if (isInvited === 'guild') {
let i = _.findIndex(member.invitations.guilds, {id: group._id});
if (i !== -1) member.invitations.guilds.splice(i, 1);
}
if (isInvited === 'party') user.invitations.party = {}; // TODO mark modified?
} else {
throw new NotFound(res.t('groupMemberNotFound'));
} }
let message = req.query.message; if (isInGroup === 'guild') _.pull(member.guilds, group._id);
if (message) _sendMessageToRemoved(group, member, message); if (isInGroup === 'party') member.party._id = undefined; // TODO remove quest information too?
return Q.all([ member.newMessages.group._id = undefined;
member.save(),
group.save(), if (group.quest && group.quest.active && group.quest.leader === member._id) {
]); member.items.quests[group.quest.key] += 1; // TODO why this?
}) }
.then(() => res.respond(200, {})) } else if (isInvited) {
.catch(next); if (isInvited === 'guild') {
let i = _.findIndex(member.invitations.guilds, {id: group._id});
if (i !== -1) member.invitations.guilds.splice(i, 1);
}
if (isInvited === 'party') user.invitations.party = {}; // TODO mark modified?
} else {
throw new NotFound(res.t('groupMemberNotFound'));
}
let message = req.query.message;
if (message) _sendMessageToRemoved(group, member, message);
await Q.all([
member.save(),
group.save(),
]);
res.respond(200, {});
}, },
}; };
@@ -571,32 +545,29 @@ api.inviteToGroup = {
method: 'POST', method: 'POST',
url: '/groups/:groupId/invite', url: '/groups/:groupId/invite',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty(); req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Group.getGroup(user, req.params.groupId, '-chat') // Do not fetch chat TODO other fields too? let group = await Group.getGroup(user, req.params.groupId, '-chat'); // Do not fetch chat TODO other fields too?
.then(group => { if (!group) throw new NotFound(res.t('groupNotFound'));
if (!group) throw new NotFound(res.t('groupNotFound'));
let uuids = req.body.uuids; let uuids = req.body.uuids;
let emails = req.body.emails; let emails = req.body.emails;
if (uuids && emails) { // TODO fix this, low priority, allow for inviting by both at the same time if (uuids && emails) { // TODO fix this, low priority, allow for inviting by both at the same time
throw new BadRequest(res.t('canOnlyInviteEmailUuid')); throw new BadRequest(res.t('canOnlyInviteEmailUuid'));
} else if (Array.isArray(uuids)) { } else if (Array.isArray(uuids)) {
// return _inviteByUUIDs(uuids, group, user, req, res, next); // return _inviteByUUIDs(uuids, group, user, req, res, next);
} else if (Array.isArray(emails)) { } else if (Array.isArray(emails)) {
// return _inviteByEmails(emails, group, user, req, res, next); // return _inviteByEmails(emails, group, user, req, res, next);
} else { } else {
throw new BadRequest(res.t('canOnlyInviteEmailUuid')); throw new BadRequest(res.t('canOnlyInviteEmailUuid'));
} }
})
.catch(next);
}, },
}; };

View File

@@ -20,18 +20,15 @@ api.createTag = {
method: 'POST', method: 'POST',
url: '/tags', url: '/tags',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
user.tags.push(Tag.sanitize(req.body)); user.tags.push(Tag.sanitize(req.body));
let savedUser = await user.save();
user.save() let l = savedUser.tags.length;
.then((savedUser) => { let tag = savedUser.tags[l - 1];
let l = savedUser.tags.length; res.respond(201, tag);
let tag = savedUser.tags[l - 1];
res.respond(201, tag);
})
.catch(next);
}, },
}; };
@@ -47,7 +44,7 @@ api.getTags = {
method: 'GET', method: 'GET',
url: '/tags', url: '/tags',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
res.respond(200, user.tags); res.respond(200, user.tags);
}, },
@@ -67,16 +64,16 @@ api.getTag = {
method: 'GET', method: 'GET',
url: '/tags/:tagId', url: '/tags/:tagId',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkParams('tagId', res.t('tagIdRequired')).notEmpty().isUUID(); req.checkParams('tagId', res.t('tagIdRequired')).notEmpty().isUUID();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
let tag = user.tags.id(req.params.tagId); let tag = user.tags.id(req.params.tagId);
if (!tag) return next(new NotFound(res.t('tagNotFound'))); if (!tag) throw new NotFound(res.t('tagNotFound'));
res.respond(200, tag); res.respond(200, tag);
}, },
}; };
@@ -95,7 +92,7 @@ api.updateTag = {
method: 'PUT', method: 'PUT',
url: '/tags/:tagId', url: '/tags/:tagId',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkParams('tagId', res.t('tagIdRequired')).notEmpty().isUUID(); req.checkParams('tagId', res.t('tagIdRequired')).notEmpty().isUUID();
@@ -104,16 +101,15 @@ api.updateTag = {
let tagId = req.params.tagId; let tagId = req.params.tagId;
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
let tag = user.tags.id(tagId); let tag = user.tags.id(tagId);
if (!tag) return next(new NotFound(res.t('tagNotFound'))); if (!tag) throw new NotFound(res.t('tagNotFound'));
_.merge(tag, Tag.sanitize(req.body)); _.merge(tag, Tag.sanitize(req.body));
user.save() let savedUser = await user.save();
.then((savedUser) => res.respond(200, savedUser.tags.id(tagId))) res.respond(200, savedUser.tags.id(tagId));
.catch(next);
}, },
}; };
@@ -131,21 +127,20 @@ api.deleteTag = {
method: 'DELETE', method: 'DELETE',
url: '/tags/:tagId', url: '/tags/:tagId',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkParams('tagId', res.t('tagIdRequired')).notEmpty().isUUID(); req.checkParams('tagId', res.t('tagIdRequired')).notEmpty().isUUID();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
let tag = user.tags.id(req.params.tagId); let tag = user.tags.id(req.params.tagId);
if (!tag) return next(new NotFound(res.t('tagNotFound'))); if (!tag) throw new NotFound(res.t('tagNotFound'));
tag.remove(); tag.remove();
user.save() await user.save();
.then(() => res.respond(200, {})) res.respond(200, {});
.catch(next);
}, },
}; };

View File

@@ -29,11 +29,11 @@ api.createTask = {
method: 'POST', method: 'POST',
url: '/tasks', url: '/tasks',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
req.checkBody('type', res.t('invalidTaskType')).notEmpty().isIn(Tasks.tasksTypes); req.checkBody('type', res.t('invalidTaskType')).notEmpty().isIn(Tasks.tasksTypes);
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
let user = res.locals.user; let user = res.locals.user;
let taskType = req.body.type; let taskType = req.body.type;
@@ -43,12 +43,12 @@ api.createTask = {
user.tasksOrder[`${taskType}s`].unshift(newTask._id); user.tasksOrder[`${taskType}s`].unshift(newTask._id);
Q.all([ let results = await Q.all([
newTask.save(), newTask.save(),
user.save(), user.save(),
]) ]);
.then((results) => res.respond(201, results[0]))
.catch(next); res.respond(201, results[0]);
}, },
}; };
@@ -67,11 +67,11 @@ api.getTasks = {
method: 'GET', method: 'GET',
url: '/tasks', url: '/tasks',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
req.checkQuery('type', res.t('invalidTaskType')).optional().isIn(Tasks.tasksTypes); req.checkQuery('type', res.t('invalidTaskType')).optional().isIn(Tasks.tasksTypes);
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
let user = res.locals.user; let user = res.locals.user;
let query = {userId: user._id}; let query = {userId: user._id};
@@ -95,16 +95,15 @@ api.getTasks = {
dateCompleted: 1, dateCompleted: 1,
}); });
Q.all([ let results = await Q.all([
queryCompleted.exec(), queryCompleted.exec(),
Tasks.Task.find(query).exec(), Tasks.Task.find(query).exec(),
]) ]);
.then((results) => res.respond(200, results[1].concat(results[0])))
.catch(next); res.respond(200, results[1].concat(results[0]));
} else { } else {
Tasks.Task.find(query).exec() let tasks = await Tasks.Task.find(query).exec();
.then((tasks) => res.respond(200, tasks)) res.respond(200, tasks);
.catch(next);
} }
}, },
}; };
@@ -123,23 +122,21 @@ api.getTask = {
method: 'GET', method: 'GET',
url: '/tasks/:taskId', url: '/tasks/:taskId',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID(); req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Tasks.Task.findOne({ let task = await Tasks.Task.findOne({
_id: req.params.taskId, _id: req.params.taskId,
userId: user._id, userId: user._id,
}).exec() }).exec();
.then((task) => {
if (!task) throw new NotFound(res.t('taskNotFound')); if (!task) throw new NotFound(res.t('taskNotFound'));
res.respond(200, task); res.respond(200, task);
})
.catch(next);
}, },
}; };
@@ -157,7 +154,7 @@ api.updateTask = {
method: 'PUT', method: 'PUT',
url: '/tasks/:taskId', url: '/tasks/:taskId',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID(); req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
@@ -165,37 +162,36 @@ api.updateTask = {
// TODO make sure tags are updated correctly (they aren't set as modified!) maybe use specific routes // TODO make sure tags are updated correctly (they aren't set as modified!) maybe use specific routes
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Tasks.Task.findOne({ let task = await Tasks.Task.findOne({
_id: req.params.taskId, _id: req.params.taskId,
userId: user._id, userId: user._id,
}).exec() }).exec();
.then((task) => {
if (!task) throw new NotFound(res.t('taskNotFound'));
// If checklist is updated -> replace the original one if (!task) throw new NotFound(res.t('taskNotFound'));
if (req.body.checklist) {
task.checklist = req.body.checklist;
delete req.body.checklist;
}
// If tags are updated -> replace the original ones // If checklist is updated -> replace the original one
if (req.body.tags) { if (req.body.checklist) {
task.tags = req.body.tags; task.checklist = req.body.checklist;
delete req.body.tags; delete req.body.checklist;
} }
// TODO we have to convert task to an object because otherwise thigns doesn't get merged correctly, very bad for performances // If tags are updated -> replace the original ones
// TODO regarding comment above make sure other models with nested fields are using this trick too if (req.body.tags) {
_.assign(task, _.merge(task.toObject(), Tasks.Task.sanitizeUpdate(req.body))); task.tags = req.body.tags;
// TODO console.log(task.modifiedPaths(), task.toObject().repeat === tep) delete req.body.tags;
// repeat is always among modifiedPaths because mongoose changes the other of the keys when using .toObject() }
// see https://github.com/Automattic/mongoose/issues/2749
return task.save(); // TODO we have to convert task to an object because otherwise thigns doesn't get merged correctly, very bad for performances
}) // TODO regarding comment above make sure other models with nested fields are using this trick too
.then((savedTask) => res.respond(200, savedTask)) _.assign(task, _.merge(task.toObject(), Tasks.Task.sanitizeUpdate(req.body)));
.catch(next); // TODO console.log(task.modifiedPaths(), task.toObject().repeat === tep)
// repeat is always among modifiedPaths because mongoose changes the other of the keys when using .toObject()
// see https://github.com/Automattic/mongoose/issues/2749
let savedTask = await task.save();
res.respond(200, savedTask);
}, },
}; };
@@ -239,81 +235,82 @@ api.scoreTask = {
method: 'POST', method: 'POST',
url: '/tasks/:taskId/score/:direction', url: '/tasks/:taskId/score/:direction',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID(); req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
req.checkParams('direction', res.t('directionUpDown')).notEmpty().isIn(['up', 'down']); // TODO what about rewards? maybe separate route? req.checkParams('direction', res.t('directionUpDown')).notEmpty().isIn(['up', 'down']); // TODO what about rewards? maybe separate route?
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
let user = res.locals.user; let user = res.locals.user;
let direction = req.params.direction; let direction = req.params.direction;
Tasks.Task.findOne({ let task = await Tasks.Task.findOne({
_id: req.params.taskId, _id: req.params.taskId,
userId: user._id, userId: user._id,
}).exec() }).exec();
.then((task) => {
if (!task) throw new NotFound(res.t('taskNotFound'));
let wasCompleted = task.completed; if (!task) throw new NotFound(res.t('taskNotFound'));
if (task.type === 'daily' || task.type === 'todo') {
task.completed = direction === 'up'; // TODO move into scoreTask
}
let delta = scoreTask({task, user, direction}, req); let wasCompleted = task.completed;
// Drop system (don't run on the client, as it would only be discarded since ops are sent to the API, not the results) if (task.type === 'daily' || task.type === 'todo') {
if (direction === 'up') user.fns.randomDrop({task, delta}, req); task.completed = direction === 'up'; // TODO move into scoreTask
}
// If a todo was completed or uncompleted move it in or out of the user.tasksOrder.todos list let delta = scoreTask({task, user, direction}, req);
if (task.type === 'todo') { // Drop system (don't run on the client, as it would only be discarded since ops are sent to the API, not the results)
if (!wasCompleted && task.completed) { if (direction === 'up') user.fns.randomDrop({task, delta}, req);
let i = user.tasksOrder.todos.indexOf(task._id);
if (i !== -1) user.tasksOrder.todos.splice(i, 1); // If a todo was completed or uncompleted move it in or out of the user.tasksOrder.todos list
} else if (wasCompleted && !task.completed) { if (task.type === 'todo') {
let i = user.tasksOrder.todos.indexOf(task._id); if (!wasCompleted && task.completed) {
if (i === -1) { let i = user.tasksOrder.todos.indexOf(task._id);
user.tasksOrder.todos.push(task._id); // TODO push at the top? if (i !== -1) user.tasksOrder.todos.splice(i, 1);
} else { // If for some reason it hadn't been removed TODO ok? } else if (wasCompleted && !task.completed) {
user.tasksOrder.todos.splice(i, 1); let i = user.tasksOrder.todos.indexOf(task._id);
user.tasksOrder.push(task._id); if (i === -1) {
} user.tasksOrder.todos.push(task._id); // TODO push at the top?
} else { // If for some reason it hadn't been removed TODO ok?
user.tasksOrder.todos.splice(i, 1);
user.tasksOrder.push(task._id);
} }
} }
}
return Q.all([ let results = await Q.all([
user.save(), user.save(),
task.save(), task.save(),
]).then((results) => { ]);
let savedUser = results[0];
let userStats = savedUser.stats.toJSON(); let savedUser = results[0];
let resJsonData = _.extend({delta, _tmp: user._tmp}, userStats);
res.respond(200, resJsonData);
sendTaskWebhook(user.preferences.webhooks, _generateWebhookTaskData(task, direction, delta, userStats, user)); let userStats = savedUser.stats.toJSON();
let resJsonData = _.extend({delta, _tmp: user._tmp}, userStats);
res.respond(200, resJsonData);
// TODO test? sendTaskWebhook(user.preferences.webhooks, _generateWebhookTaskData(task, direction, delta, userStats, user));
if (task.challenge.id && task.challenge.taskId && !task.challenge.broken && task.type !== 'reward') {
Tasks.Task.findOne({
_id: task.challenge.taskId,
}).exec()
.then(chalTask => {
chalTask.value += delta;
if (chalTask.type === 'habit' || chalTask.type === 'daily') {
chalTask.history.push({value: chalTask.value, date: Number(new Date())});
// TODO 1. treat challenges as subscribed users for preening 2. it's expensive to do it at every score - how to have it happen once like for cron?
chalTask.history = preenHistory(user, chalTask.history);
chalTask.markModified('history');
}
return chalTask.save(); // TODO test?
}); if (task.challenge.id && task.challenge.taskId && !task.challenge.broken && task.type !== 'reward') {
// .catch(next) TODO what to do here // Wrapping everything in a try/catch block because if an error occurs using `await` it MUST NOT bubble up because the request has already been handled
try {
let chalTask = await Tasks.Task.findOne({
_id: task.challenge.taskId,
}).exec();
chalTask.value += delta;
if (chalTask.type === 'habit' || chalTask.type === 'daily') {
chalTask.history.push({value: chalTask.value, date: Number(new Date())});
// TODO 1. treat challenges as subscribed users for preening 2. it's expensive to do it at every score - how to have it happen once like for cron?
chalTask.history = preenHistory(user, chalTask.history);
chalTask.markModified('history');
} }
});
}) await chalTask.save();
.catch(next); } catch (e) {
// TODO handle
}
}
}, },
}; };
@@ -334,41 +331,39 @@ api.moveTask = {
method: 'POST', method: 'POST',
url: '/tasks/move/:taskId/to/:position', url: '/tasks/move/:taskId/to/:position',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID(); req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
req.checkParams('position', res.t('positionRequired')).notEmpty().isNumeric(); req.checkParams('position', res.t('positionRequired')).notEmpty().isNumeric();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
let user = res.locals.user; let user = res.locals.user;
let to = Number(req.params.position); let to = Number(req.params.position);
Tasks.Task.findOne({ let task = await Tasks.Task.findOne({
_id: req.params.taskId, _id: req.params.taskId,
userId: user._id, userId: user._id,
}).exec() }).exec();
.then((task) => {
if (!task) throw new NotFound(res.t('taskNotFound'));
if (task.type === 'todo' && task.completed) throw new NotFound(res.t('cantMoveCompletedTodo'));
let order = user.tasksOrder[`${task.type}s`];
let currentIndex = order.indexOf(task._id);
// If for some reason the task isn't ordered (should never happen) if (!task) throw new NotFound(res.t('taskNotFound'));
// or if the task is moved to a non existing position if (task.type === 'todo' && task.completed) throw new NotFound(res.t('cantMoveCompletedTodo'));
// or if the task is moved to postion -1 (push to bottom) let order = user.tasksOrder[`${task.type}s`];
// -> push task at end of list let currentIndex = order.indexOf(task._id);
if (currentIndex === -1 || !order[to] || to === -1) {
order.push(task._id);
} else {
let taskToMove = order.splice(currentIndex, 1)[0];
order.splice(to, 0, taskToMove);
}
return user.save(); // If for some reason the task isn't ordered (should never happen)
}) // or if the task is moved to a non existing position
.then(() => res.respond(200, {})) // TODO what to return // or if the task is moved to postion -1 (push to bottom)
.catch(next); // -> push task at end of list
if (currentIndex === -1 || !order[to] || to === -1) {
order.push(task._id);
} else {
let taskToMove = order.splice(currentIndex, 1)[0];
order.splice(to, 0, taskToMove);
}
await user.save();
res.respond(200, {}); // TODO what to return
}, },
}; };
@@ -386,28 +381,27 @@ api.addChecklistItem = {
method: 'POST', method: 'POST',
url: '/tasks/:taskId/checklist', url: '/tasks/:taskId/checklist',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID(); req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
// TODO check that req.body isn't empty and is an array // TODO check that req.body isn't empty and is an array
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Tasks.Task.findOne({ let task = await Tasks.Task.findOne({
_id: req.params.taskId, _id: req.params.taskId,
userId: user._id, userId: user._id,
}).exec() }).exec();
.then((task) => {
if (!task) throw new NotFound(res.t('taskNotFound'));
if (task.type !== 'daily' && task.type !== 'todo') throw new BadRequest(res.t('checklistOnlyDailyTodo'));
task.checklist.push(Tasks.Task.sanitizeChecklist(req.body)); if (!task) throw new NotFound(res.t('taskNotFound'));
return task.save(); if (task.type !== 'daily' && task.type !== 'todo') throw new BadRequest(res.t('checklistOnlyDailyTodo'));
})
.then((savedTask) => res.respond(200, savedTask)) // TODO what to return task.checklist.push(Tasks.Task.sanitizeChecklist(req.body));
.catch(next); let savedTask = await task.save();
res.respond(200, savedTask); // TODO what to return
}, },
}; };
@@ -426,31 +420,30 @@ api.scoreCheckListItem = {
method: 'POST', method: 'POST',
url: '/tasks/:taskId/checklist/:itemId/score', url: '/tasks/:taskId/checklist/:itemId/score',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID(); req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
req.checkParams('itemId', res.t('itemIdRequired')).notEmpty().isUUID(); req.checkParams('itemId', res.t('itemIdRequired')).notEmpty().isUUID();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Tasks.Task.findOne({ let task = await Tasks.Task.findOne({
_id: req.params.taskId, _id: req.params.taskId,
userId: user._id, userId: user._id,
}).exec() }).exec();
.then((task) => {
if (!task) throw new NotFound(res.t('taskNotFound'));
if (task.type !== 'daily' && task.type !== 'todo') throw new BadRequest(res.t('checklistOnlyDailyTodo'));
let item = _.find(task.checklist, {_id: req.params.itemId}); if (!task) throw new NotFound(res.t('taskNotFound'));
if (task.type !== 'daily' && task.type !== 'todo') throw new BadRequest(res.t('checklistOnlyDailyTodo'));
if (!item) throw new NotFound(res.t('checklistItemNotFound')); let item = _.find(task.checklist, {_id: req.params.itemId});
item.completed = !item.completed;
return task.save(); if (!item) throw new NotFound(res.t('checklistItemNotFound'));
}) item.completed = !item.completed;
.then((savedTask) => res.respond(200, savedTask)) // TODO what to return let savedTask = await task.save();
.catch(next);
res.respond(200, savedTask); // TODO what to return
}, },
}; };
@@ -469,31 +462,30 @@ api.updateChecklistItem = {
method: 'PUT', method: 'PUT',
url: '/tasks/:taskId/checklist/:itemId', url: '/tasks/:taskId/checklist/:itemId',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID(); req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
req.checkParams('itemId', res.t('itemIdRequired')).notEmpty().isUUID(); req.checkParams('itemId', res.t('itemIdRequired')).notEmpty().isUUID();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Tasks.Task.findOne({ let task = await Tasks.Task.findOne({
_id: req.params.taskId, _id: req.params.taskId,
userId: user._id, userId: user._id,
}).exec() }).exec();
.then((task) => {
if (!task) throw new NotFound(res.t('taskNotFound'));
if (task.type !== 'daily' && task.type !== 'todo') throw new BadRequest(res.t('checklistOnlyDailyTodo'));
let item = _.find(task.checklist, {_id: req.params.itemId}); if (!task) throw new NotFound(res.t('taskNotFound'));
if (!item) throw new NotFound(res.t('checklistItemNotFound')); if (task.type !== 'daily' && task.type !== 'todo') throw new BadRequest(res.t('checklistOnlyDailyTodo'));
_.merge(item, Tasks.Task.sanitizeChecklist(req.body)); let item = _.find(task.checklist, {_id: req.params.itemId});
return task.save(); if (!item) throw new NotFound(res.t('checklistItemNotFound'));
})
.then((savedTask) => res.respond(200, savedTask)) // TODO what to return _.merge(item, Tasks.Task.sanitizeChecklist(req.body));
.catch(next); let savedTask = await task.save();
res.respond(200, savedTask); // TODO what to return
}, },
}; };
@@ -512,31 +504,30 @@ api.removeChecklistItem = {
method: 'DELETE', method: 'DELETE',
url: '/tasks/:taskId/checklist/:itemId', url: '/tasks/:taskId/checklist/:itemId',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID(); req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
req.checkParams('itemId', res.t('itemIdRequired')).notEmpty().isUUID(); req.checkParams('itemId', res.t('itemIdRequired')).notEmpty().isUUID();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Tasks.Task.findOne({ let task = await Tasks.Task.findOne({
_id: req.params.taskId, _id: req.params.taskId,
userId: user._id, userId: user._id,
}).exec() }).exec();
.then((task) => {
if (!task) throw new NotFound(res.t('taskNotFound'));
if (task.type !== 'daily' && task.type !== 'todo') throw new BadRequest(res.t('checklistOnlyDailyTodo'));
let itemI = _.findIndex(task.checklist, {_id: req.params.itemId}); if (!task) throw new NotFound(res.t('taskNotFound'));
if (itemI === -1) throw new NotFound(res.t('checklistItemNotFound')); if (task.type !== 'daily' && task.type !== 'todo') throw new BadRequest(res.t('checklistOnlyDailyTodo'));
task.checklist.splice(itemI, 1); let itemI = _.findIndex(task.checklist, {_id: req.params.itemId});
return task.save(); if (itemI === -1) throw new NotFound(res.t('checklistItemNotFound'));
})
.then(() => res.respond(200, {})) // TODO what to return task.checklist.splice(itemI, 1);
.catch(next);
await task.save();
res.respond(200, {}); // TODO what to return
}, },
}; };
@@ -555,7 +546,7 @@ api.addTagToTask = {
method: 'POST', method: 'POST',
url: '/tasks/:taskId/tags/:tagId', url: '/tasks/:taskId/tags/:tagId',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID(); req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
@@ -563,24 +554,23 @@ api.addTagToTask = {
req.checkParams('tagId', res.t('tagIdRequired')).notEmpty().isUUID().isIn(userTags); req.checkParams('tagId', res.t('tagIdRequired')).notEmpty().isUUID().isIn(userTags);
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Tasks.Task.findOne({ let task = await Tasks.Task.findOne({
_id: req.params.taskId, _id: req.params.taskId,
userId: user._id, userId: user._id,
}).exec() }).exec();
.then((task) => {
if (!task) throw new NotFound(res.t('taskNotFound'));
let tagId = req.params.tagId;
let alreadyTagged = task.tags.indexOf(tagId) !== -1; if (!task) throw new NotFound(res.t('taskNotFound'));
if (alreadyTagged) throw new BadRequest(res.t('alreadyTagged')); let tagId = req.params.tagId;
task.tags.push(tagId); let alreadyTagged = task.tags.indexOf(tagId) !== -1;
return task.save(); if (alreadyTagged) throw new BadRequest(res.t('alreadyTagged'));
})
.then((savedTask) => res.respond(200, savedTask)) // TODO what to return task.tags.push(tagId);
.catch(next);
let savedTask = await task.save();
res.respond(200, savedTask); // TODO what to return
}, },
}; };
@@ -599,30 +589,29 @@ api.removeTagFromTask = {
method: 'DELETE', method: 'DELETE',
url: '/tasks/:taskId/tags/:tagId', url: '/tasks/:taskId/tags/:tagId',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID(); req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
req.checkParams('tagId', res.t('tagIdRequired')).notEmpty().isUUID(); req.checkParams('tagId', res.t('tagIdRequired')).notEmpty().isUUID();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Tasks.Task.findOne({ let task = await Tasks.Task.findOne({
_id: req.params.taskId, _id: req.params.taskId,
userId: user._id, userId: user._id,
}).exec() }).exec();
.then((task) => {
if (!task) throw new NotFound(res.t('taskNotFound'));
let tagI = task.tags.indexOf(req.params.tagId); if (!task) throw new NotFound(res.t('taskNotFound'));
if (tagI === -1) throw new NotFound(res.t('tagNotFound'));
task.tags.splice(tagI, 1); let tagI = task.tags.indexOf(req.params.tagId);
return task.save(); if (tagI === -1) throw new NotFound(res.t('tagNotFound'));
})
.then(() => res.respond(200, {})) // TODO what to return task.tags.splice(tagI, 1);
.catch(next);
await task.save();
res.respond(200, {}); // TODO what to return
}, },
}; };
@@ -656,30 +645,26 @@ api.deleteTask = {
method: 'DELETE', method: 'DELETE',
url: '/tasks/:taskId', url: '/tasks/:taskId',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
handler (req, res, next) { async handler (req, res) {
let user = res.locals.user; let user = res.locals.user;
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID(); req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
let validationErrors = req.validationErrors(); let validationErrors = req.validationErrors();
if (validationErrors) return next(validationErrors); if (validationErrors) throw validationErrors;
Tasks.Task.findOne({ let task = await Tasks.Task.findOne({
_id: req.params.taskId, _id: req.params.taskId,
userId: user._id, userId: user._id,
}).exec() }).exec();
.then((task) => {
if (!task) throw new NotFound(res.t('taskNotFound'));
if (task.challenge.id) throw new NotAuthorized(res.t('cantDeleteChallengeTasks'));
_removeTaskTasksOrder(user, req.params.taskId); if (!task) throw new NotFound(res.t('taskNotFound'));
return Q.all([ if (task.challenge.id) throw new NotAuthorized(res.t('cantDeleteChallengeTasks'));
user.save(),
task.remove(), _removeTaskTasksOrder(user, req.params.taskId);
]); await Q.all([user.save(), task.remove()]);
})
.then(() => res.respond(200, {})) res.respond(200, {});
.catch(next);
}, },
}; };

View File

@@ -16,7 +16,7 @@ api.getUser = {
method: 'GET', method: 'GET',
middlewares: [authWithHeaders(), cron], middlewares: [authWithHeaders(), cron],
url: '/user', url: '/user',
handler (req, res) { async handler (req, res) {
let user = res.locals.user.toJSON(); let user = res.locals.user.toJSON();
// Remove apiToken from resonse TODO make it priavte at the user level? returned in signup/login // Remove apiToken from resonse TODO make it priavte at the user level? returned in signup/login