addCommentTag mutation works

This commit is contained in:
Benjamin Goering
2017-02-28 19:59:32 +08:00
parent fc9c67b05c
commit 6e338290a1
16 changed files with 523 additions and 379 deletions
+37 -16
View File
@@ -4,7 +4,8 @@ const ActionModel = require('../models/action');
const ActionsService = require('./actions');
const ALLOWED_TAGS = [
{name: 'STAFF'}
'STAFF',
'BEST',
];
const STATUSES = [
@@ -44,29 +45,49 @@ module.exports = class CommentsService {
/**
* Adds a tag if it doesn't already exist on the comment.
* @param {String} id the id of the comment to tag
* @param {String} name the name of the tag to add
* @param {String} assigned_by the user id for the user who added the tag
*/
static addTag(id, name, assigned_by) {
if (ALLOWED_TAGS.find((t) => t.name === name) == null) {
if (ALLOWED_TAGS.find((t) => t === name) == null) {
return Promise.reject(new Error('tag not allowed'));
}
return CommentModel.update({
const filter = {
id,
tags: {
$ne: {
name
tags: {$not: {$elemMatch: {name}}}
};
const update = {
$push: {tags: {
name,
assigned_by,
created_at: new Date()
}}
};
return CommentModel.update(filter, update)
.then(({nModified}) => {
switch (nModified) {
case 0:
// either the tag was already there, or the comment doesn't exist with that id...
return this.findById(id)
.then(result => {
if ( ! result) {
throw new Error(`Can't add tag to comment. There is no comment with id ${id}`);
}
throw new Error(`Can't add tag ${name} to comment. Comment already has that tag.`);
});
case 1:
// tag added
return;
default:
console.warn('CommentsService#addTag modified multiple comments, but it should only have modified 1. '
+ `You may have bad data. Check for multiple comments with id=${id}`);
}
}
}, {
$push: {
tags: {
name,
assigned_by,
created_at: new Date()
}
}
});
});
}
/**