Skip to content

Commit

Permalink
Merge b4d787e into d577ac2
Browse files Browse the repository at this point in the history
  • Loading branch information
nshutijonathan committed Aug 17, 2019
2 parents d577ac2 + b4d787e commit 1b621d7
Show file tree
Hide file tree
Showing 11 changed files with 400 additions and 71 deletions.
152 changes: 83 additions & 69 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"swagger-jsdoc": "^3.3.0",
"swagger-ui-express": "^4.0.7",
"uniqid": "^5.0.3",
"validator": "^11.1.0",
"winston": "^3.2.1"
},
"devDependencies": {
Expand Down
152 changes: 152 additions & 0 deletions src/controllers/comments.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import Sequelize from 'sequelize';
import commentsService from '../services/comments.service';
import UserService from '../services/user.service';
import models from '../models';
const CommentsDb = models.Comment;
const database = models.Article;
/**
*
*
* @class Comments
*/
class Comments {
/**
*
*
* @static
* @param {*} req
* @param {*} res
* @returns {object} data
* @memberof Comments
*/
static async createComment(req, res) {
const userId = req.auth.id;
const getUser = await UserService.getOneUser(userId);
const getArticle = await database.findOne({
where: { slug: req.params.slug }
});
if (!getUser) return res.status(404).send({ message: `User with id ${req.auth.id} not found` });
if (!getArticle) return res.status(404).send({ message: `Article with slug ${req.params.slug} not found` });
try {
const comment = {
articleSlug: getArticle.slug,
userId: req.auth.id,
body: req.body.body,
parentCommentId: req.body.parentCommentId,
};
const createdComment = await commentsService.addComment(comment);
return res.status(201).send({
status: 201,
message: 'Comment successfully created',
comment: createdComment
});
} catch (error) {
return res.send({
message: error.message
});
}
}

/**
*
*
* @static
* @param {*} req
* @param {*} res
* @returns {object} data
* @memberof Comments
*/
static async deleteComment(req, res) {
const userId = req.auth.id;
const getUser = await CommentsDb.findOne({ where: { userId } });
const commentAuthor = getUser && getUser.get().userId;
const { id } = req.params;

if (!Number(id)) {
return res.status(400).send({
status: 400,
message: 'Please provide numeric value'
});
}
if (!(req.auth.id === commentAuthor)) {
return res.status(403).send({
status: 403,
message: 'comment is not yours'
});
}
try {
const CommentTODelete = await commentsService.deleteComment(id);
if (CommentTODelete) {
return res.status(200).send({
status: 200,
message: `Comment with id ${id} is successfully deleted`
});
}

return res.status(404).send({
status: 404,
message: `Comment with id ${id} is not found`
});
} catch (error) {
return res.send({
message: error.message
});
}
}

/**
*
*
* @static
* @param {*} req
* @param {*} res
* @returns {object} data
* @memberof Comments
*/
static async getComments(req, res) {
const comments = await CommentsDb.findAll();
if (!comments) {
return res.status(200).send({
message: 'No comments found'
});
}
return res.status(200).send({
status: 200,
message: 'All comments successfully retrieved',
comments
});
}

/**
*
*
* @static
* @param {*} req
* @param {*} res
* @returns {Object} return comment updation message
* @memberof UserController
*/
static async updateComment(req, res) {
const getComment = await CommentsDb.findOne({ where: { id: req.params.id } });
const gottenComent = getComment && getComment.get().id;
const { id } = req.params;
if (!id) {
return res.status(400).send({
status: 400,
message: 'Please provide valid numeric value'
});
}
if (!gottenComent) {
return res.status(200).json({ status: 200, message: 'That comment does not exist' });
}

const { body } = req.body;
const updateComment = await commentsService.updateComment(req.params.id, { body });
return res.status(200).send({
status: 200,
message: 'Updation is successfully',
updateComment
});
}
}
export default Comments;
11 changes: 11 additions & 0 deletions src/middlewares/validators/comments.body.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import validator from 'validator';

const CommentValidation = (req, res, next) => {
if (validator.isEmpty(req.body.body)) {
return res.status(400).send({
message: 'Comment body is required'
});
}
next();
};
export default CommentValidation;
41 changes: 41 additions & 0 deletions src/migrations/20190816101310-create-comment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { sequelize } from '../models';

'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Comments', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
userId: {
type: Sequelize.INTEGER
},
articleSlug: {
type: Sequelize.STRING
},
body: {
type: Sequelize.STRING
},
parentCommentId: {
type: Sequelize.INTEGER,
allowNull: true
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
}) .then(() => sequelize.query(`ALTER TABLE "Comments"
ADD CONSTRAINT fk_parentReference FOREIGN KEY ("parentCommentId")
REFERENCES "Comments" (id) ON DELETE CASCADE`));
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Comments');
}
};
28 changes: 28 additions & 0 deletions src/models/comment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'use strict';
module.exports = (sequelize, DataTypes) => {
const Comment = sequelize.define('Comment', {
userId: DataTypes.INTEGER,
articleSlug: {
type: DataTypes.STRING,
allowNull: false,
references: {
model: 'Articles',
key: 'slug'
},
onUpdate: 'CASCADE',
onDelete: 'CASCADE'
},
parentCommentId: {
type: DataTypes.INTEGER,
allowNull: true
},
body: DataTypes.STRING
}, {});
Comment.associate = function(models) {
// associations can be defined here
Comment.belongsTo(models.user,{
foreignKey:'id',as:'commentAuthor'
});
};
return Comment;
};
2 changes: 2 additions & 0 deletions src/models/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,6 @@ Object.keys(db).forEach((modelName) => {
db.sequelize = sequelize;
db.Sequelize = Sequelize;

export { sequelize };

module.exports = db;
4 changes: 2 additions & 2 deletions src/routes/api/article/article.routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ router.post('/fake', auth, fakeCloud, validate(schema.articleSchema), articleCon
router.post('/articles', [auth, confirmEmailAuth], imageUpload.array('images', 10), validate(schema.articleSchema), articleController.createArticles);
router.get('/articles', [auth, confirmEmailAuth], articleController.getAllArticles);
router.get('/articles/:slug', [auth, confirmEmailAuth], articleController.getOneArticle);
router.delete('/articles/:slug', [auth, confirmEmailAuth], articleController.deleteArticle);
router.patch('/articles/:slug', [auth, confirmEmailAuth], imageUpload.array('images', 10), articleController.UpdateArticle);
router.delete('articles/:slug', [auth, confirmEmailAuth], articleController.deleteArticle);
router.patch('articles/:slug', [auth, confirmEmailAuth], imageUpload.array('images', 10), articleController.UpdateArticle);
export default router;
11 changes: 11 additions & 0 deletions src/routes/api/comment/comments.route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import express from 'express';
import Comments from '../../../controllers/comments.controller';
import auth from '../../../middlewares/auth';
import CommentsValidation from '../../../middlewares/validators/comments.body';

const router = express.Router();
router.post('/:slug', [auth, CommentsValidation], Comments.createComment);
router.get('/', [auth], Comments.getComments);
router.delete('/:id', [auth], Comments.deleteComment);
router.put('/:id', [auth, CommentsValidation], Comments.updateComment);
export default router;
2 changes: 2 additions & 0 deletions src/routes/api/index.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ import user from './user/user.route';
import article from './article/article.routes';
import profile from './profile/profile.route';
import rate from './rate/rate.route';
import Comments from './comment/comments.route';

const router = express.Router();
router.use('/images', express.static(path.join(__dirname, 'images')));

router.use('/comments', Comments);
router.use(oauth);
router.use('/profile', profile);
router.use('/users', user);
Expand Down
67 changes: 67 additions & 0 deletions src/services/comments.service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import models from '../models';

const database = models.Comment;
/**
*
*
* @class commentsService
*/
class commentsService {
/**
*
*
* @static
* @param {*} comment
* @returns {object} data
* @memberof commentsService
*/
static async addComment(comment) {
try {
return await database.create(comment);
} catch (error) {
throw error;
}
}

/**
*
*
* @static
* @param {*} id
* @returns {object} data
* @memberof commentsService
*/
static async deleteComment(id) {
try {
const CommentToDelete = await database.findOne({ where: { id: Number(id) } });
if (CommentToDelete) {
const deletedComment = await database.destroy({
where: { id: Number(id) }
});
return deletedComment;
}
return null;
} catch (error) {
throw error;
}
}

/**
*
*
* @static
* @param {*} id
* @param {*} updateComments
* @returns {object} data
* @memberof commentsService
*/
static async updateComment(id, updateComments) {
try {
const results = await database.update(updateComments, { where: { id }, returning: true });
return results;
} catch (error) {
throw error;
}
}
}
export default commentsService;

0 comments on commit 1b621d7

Please sign in to comment.