Skip to content
This repository has been archived by the owner on May 9, 2021. It is now read-only.

Commit

Permalink
feature(commentController): improve controller
Browse files Browse the repository at this point in the history
- improve getCommentsCount helper
- remove articleId from CommentReply models

[Finishes #162167286]
  • Loading branch information
KvNGCzA committed Nov 28, 2018
1 parent d03544e commit b85e073
Show file tree
Hide file tree
Showing 13 changed files with 86 additions and 146 deletions.
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ cache:
directories:
- "node_modules"
before_script:
- psql -c 'create database valinor_backend_test;' -U postgres
- npm run db-migrate && npm run db-seed-all
after_script:
- npm run db-undo-migrate
Expand Down
6 changes: 5 additions & 1 deletion server/config/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ export default {
dialect: 'postgres',
},
test: {
use_env_variable: 'DB_DATABASE_TEST_URL',
username: 'postgres',
password: '',
database: 'valinor_backend_test',
host: '127.0.0.1',
port: '5432',
dialect: 'postgres',
},
production: {
Expand Down
2 changes: 1 addition & 1 deletion server/controllers/ArticleController.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ class ArticleController {
as: 'replies',
attributes: [
'id',
'reply',
'body',
'createdAt',
'updatedAt'
],
Expand Down
23 changes: 8 additions & 15 deletions server/controllers/CommentController.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,22 +70,15 @@ class CommentController {
* @param {object} next
* @returns {object} returns an object of comment
*/
static async addCommentToComment(req, res, next) {
static async addCommentToComment(req, res) {
const { id } = req.userData;
const { articleId, commentId } = req.params;
const { reply } = req.body;
let result;
const { commentId } = req.params;
const { body } = req.body;
let reply;
let commenter;
try {
const comment = await Comment.findByPk(commentId);
if (comment.articleId !== +articleId) {
const err = new Error('this comment does not belong to this article');
err.status = 400;
return next(err);
}
result = await CommentReply.create({
reply,
articleId,
reply = await CommentReply.create({
body,
commentId,
userId: id
});
Expand All @@ -105,11 +98,11 @@ class CommentController {
} catch (error) {
return error;
}
result.dataValues.commenter = commenter;
reply.dataValues.commenter = commenter;
return res.status(201).json({
status: 'success',
message: 'reply successfully added',
comment: result,
reply,
});
}

Expand Down
13 changes: 7 additions & 6 deletions server/helpers/getCommentsCount.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import models from '../models';
import extractId from './extractId';

const { Comment, CommentReply } = models;

Expand All @@ -12,16 +13,16 @@ const getCommentsCount = async (arr) => {
const comments = arr.map(articleId => Comment.findAll({
where: { articleId }
}));
const commentReplies = arr.map(articleId => CommentReply.findAll({
where: { articleId }
}));
const commentCount = await Promise.all(comments);
const replies = commentCount.map(comment => extractId(comment));
const commentReplies = replies.map(commentId => CommentReply.findAll({
where: { commentId }
}));
const replyCount = await Promise.all(commentReplies);
const commentCountArray = commentCount.map(x => x.length);
const replyCountArray = replyCount.map(x => x.length);
const result = commentCountArray.map(
(x, index) => x + replyCountArray[index]
);
const result = commentCountArray
.map((x, index) => x + replyCountArray[index]);
return result;
};

Expand Down
74 changes: 14 additions & 60 deletions server/middlewares/ArticleValidation.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,20 @@ class ArticleValidation {
* @returns {void}
*/
static validateBody(req) {
req.checkBody('body', 'please enter a body').exists();
req.checkBody(
'body',
'please provide a body'
).exists();

if (req.body.body) {
req.checkBody(
'body',
'please provide a body'
).custom((body) => {
const text = body.trim();
if (text !== '') return true;
});
}
}

/**
Expand Down Expand Up @@ -217,49 +230,6 @@ class ArticleValidation {
).optional({ checkFalsy: false }).isAlpha();
}

/**
* This method validates the comment id
* @param {object} req - The request object
* @returns {void}
*/
static validateCommentId(req) {
req.checkParams(
'commentId',
'commentId must be an integer'
).isInt();
req.checkParams(
'commentId',
'commentId must be greater than 0'
).isInt({ gt: 0 });
}

/**
* This method validates the articleId
* @param {object} req - The request object
* @returns {void}
*/
static validateArticleId(req) {
req.checkParams(
'articleId',
'articleId must be an integer'
).isInt();
req.checkParams(
'articleId',
'articleId must be greater than 0'
).isInt({ gt: 0 });
}

/**
* This method validates the comment reply
* @param {object} req - The request object
* @returns {void}
*/
static validateCommentReply(req) {
req.checkBody(
'reply',
'please provide a reply'
).exists();
}

/**
* @description - This method validates the article page queries.
Expand Down Expand Up @@ -306,22 +276,6 @@ class ArticleValidation {
ArticleValidation.validateReportBody(req);
sendFormattedError(req, res, next, 400);
}

/**
* @description - This method validates comment reply input and param.
* @param {object} req - The request object to be validated.
* @param {object} res - Th response object to be validated.
* @param {object} next - The callback function to the next middleware.
* @returns {object} - The error object with message.
* @memberOf ArticleValidators
* @static
*/
static validateCommentReplyInput(req, res, next) {
ArticleValidation.validateCommentId(req);
ArticleValidation.validateCommentReply(req);
ArticleValidation.validateArticleId(req);
sendFormattedError(req, res, next, 400);
}
}

export default ArticleValidation;
18 changes: 4 additions & 14 deletions server/migrations/20181123164359-create-comment-reply.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
export default {
up: (queryInterface, Sequelize) => queryInterface.createTable(
'CommentReplies', {
up: (queryInterface, Sequelize) => queryInterface
.createTable('CommentReplies', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
reply: {
body: {
type: Sequelize.STRING
},
commentId: {
Expand All @@ -28,15 +28,6 @@ export default {
key: 'id'
}
},
articleId: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
allowNull: false,
references: {
model: 'Articles',
key: 'id'
}
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
Expand All @@ -45,7 +36,6 @@ export default {
allowNull: false,
type: Sequelize.DATE
}
}
),
}),
down: queryInterface => queryInterface.dropTable('CommentReplies')
};
6 changes: 1 addition & 5 deletions server/models/article.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,7 @@ export default (sequelize, DataTypes) => {
Category,
ArticleTag,
Bookmark,
ReadingStats,
CommentReply
ReadingStats
} = models;
Article.belongsTo(User, {
as: 'author',
Expand Down Expand Up @@ -104,9 +103,6 @@ export default (sequelize, DataTypes) => {
Article.hasMany(ReadingStats, {
foreignKey: 'userId'
});
Article.hasMany(CommentReply, {
foreignKey: 'articleId'
});
};
return Article;
};
8 changes: 2 additions & 6 deletions server/models/commentreply.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
export default (sequelize, DataTypes) => {
const CommentReply = sequelize.define('CommentReply', {
reply: {
body: {
type: DataTypes.STRING,
allowNull: false
}
});
CommentReply.associate = (models) => {
const { User, Comment, Article } = models;
const { User, Comment } = models;
CommentReply.belongsTo(User, {
foreignKey: 'userId',
as: 'commenter',
Expand All @@ -17,10 +17,6 @@ export default (sequelize, DataTypes) => {
as: 'replies',
onDelete: 'CASCADE'
});
CommentReply.belongsTo(Article, {
foreignKey: 'articleId',
onDelete: 'CASCADE'
});
};
return CommentReply;
};
7 changes: 3 additions & 4 deletions server/routes/api/comments.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ import validateAccess from '../../middlewares/validateAccess';
const comments = express.Router();

const {
validateArticleCommentInput,
validateCommentReplyInput
validateArticleCommentInput
} = ArticleCommentValidation;
const {
addCommentOnArticle,
Expand All @@ -33,9 +32,9 @@ comments.post(

// post a comment on a comment
comments.post(
'/articles/:articleId/comments/:commentId',
'/articles/comments/:commentId',
verifyToken,
validateCommentReplyInput,
validateArticleCommentInput,
validateResourceId,
addCommentToComment
);
Expand Down
12 changes: 4 additions & 8 deletions server/seeders/20181115144729-comment-reply.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,29 @@
export default {
up: queryInterface => queryInterface.bulkInsert('CommentReplies', [{
reply: 'Plagiarism is bad',
body: 'Plagiarism is bad',
userId: 1,
commentId: 1,
articleId: 1,
createdAt: new Date(),
updatedAt: new Date()
},
{
reply: 'User Agreement is bad',
body: 'User Agreement is bad',
userId: 1,
commentId: 1,
articleId: 1,
createdAt: new Date(),
updatedAt: new Date()
},
{
reply: 'Policy is bad',
body: 'Policy is bad',
userId: 1,
commentId: 1,
articleId: 1,
createdAt: new Date(),
updatedAt: new Date()
},
{
reply: 'Policy is bad',
body: 'Policy is bad',
userId: 1,
commentId: 3,
articleId: 2,
createdAt: new Date(),
updatedAt: new Date()
}], {}),
Expand Down
12 changes: 11 additions & 1 deletion test/server/controllers/ArticleController.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ chai.use(chaiHttp);

const articleBaseUrl = '/api/v1/articles';
const getAnArticleUrl = string => `${articleBaseUrl}/${string}`;

const expiredToken = createToken(1, 1);
describe('Articles Controller Tests', () => {
const userData = {};
let articleData = {};
Expand Down Expand Up @@ -937,5 +937,15 @@ describe('Articles Controller Tests', () => {
done();
});
});
it('should fail due to expired token', (done) => {
chai.request(app)
.post(`${articleBaseUrl}/2/reports`)
.set('authorization', expiredToken)
.send(articleReportData)
.end((err, res) => {
res.status.should.be.eql(401);
done();
});
});
});
});
Loading

0 comments on commit b85e073

Please sign in to comment.