From c637be364a32baabc4b8062fe25ac32476ab0d8b Mon Sep 17 00:00:00 2001 From: Wyatt Johnson Date: Fri, 10 Feb 2017 12:00:50 -0700 Subject: [PATCH] Moved tag creation into mutator --- graph/mutators/comment.js | 6 ++++ services/comments.js | 60 +++++++++++++++++++++++++++------------ services/users.js | 14 --------- 3 files changed, 48 insertions(+), 32 deletions(-) diff --git a/graph/mutators/comment.js b/graph/mutators/comment.js index 3c35b0e60..8e3510920 100644 --- a/graph/mutators/comment.js +++ b/graph/mutators/comment.js @@ -36,6 +36,12 @@ const createComment = ({user, loaders: {Comments}}, {body, asset_id, parent_id = } } + if (user.hasRoles('ADMIN')) { + return CommentsService + .addTag(comment.id, 'STAFF', user.id) + .then(() => comment); + } + return comment; }); }; diff --git a/services/comments.js b/services/comments.js index 876128c47..fc05341cb 100644 --- a/services/comments.js +++ b/services/comments.js @@ -3,7 +3,9 @@ const CommentModel = require('../models/comment'); const ActionModel = require('../models/action'); const ActionsService = require('./actions'); -const UsersService = require('./users'); +const ALLOWED_TAGS = [ + {name: 'STAFF'} +]; module.exports = class CommentsService { @@ -27,24 +29,46 @@ module.exports = class CommentsService { author_id } = comment; - return UsersService.isStaff(author_id).then((isStaff) => { - comment = new CommentModel({ - body, - asset_id, - parent_id, - status_history: status ? [{ - type: status, + comment = new CommentModel({ + body, + asset_id, + parent_id, + status_history: status ? [{ + type: status, + created_at: new Date() + }] : [], + tags: [], + status, + author_id + }); + + return comment.save(); + } + + /** + * Adds a tag if it doesn't already exist on the comment. + */ + static addTag(id, name, assigned_by) { + + if (ALLOWED_TAGS.find((t) => t.name === name) == null) { + return Promise.reject(new Error('tag not allowed')); + } + + return CommentModel.update({ + id, + tags: { + $ne: { + name + } + } + }, { + $push: { + tags: { + name, + assigned_by, created_at: new Date() - }] : [], - status, - tags: isStaff ? [{ - name: 'STAFF', - assigned_by: null, - created_at: new Date() - }] : [], - author_id - }); - return comment.save(); + } + } }); } diff --git a/services/users.js b/services/users.js index 9d3d57532..408d5c618 100644 --- a/services/users.js +++ b/services/users.js @@ -687,18 +687,4 @@ module.exports = class UsersService { Promise.reject(new Error('You do not have permission to update your username.')); }); } - - /** - * Returns true if the user is staff. - * @param {String} id the id of the user to be enabled. - * @return {Promise} - */ - static isStaff(id) { - return UsersService.findById(id).then((user) => { - if (user) { - return user.hasRoles('ADMIN'); - } - return false; - }); - } };