Skip to content

Commit

Permalink
chore(refactor): refactor comment model and controller
Browse files Browse the repository at this point in the history
  - refactor comment model and controller to use
articleId and userId as foreignKeys
[Delivers #159204723]
  • Loading branch information
madeofhuman committed Aug 14, 2018
1 parent 2596051 commit bb2dead
Show file tree
Hide file tree
Showing 16 changed files with 93 additions and 82 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
"start": "babel-node server/index.js --presets babel-preset-env",
"dev": "nodemon server/index.js --exec babel-node --presets babel-preset-env",
"migrate:test": "sequelize db:migrate:undo:all --env=test && sequelize db:migrate --env=test && sequelize db:seed:all --env=test",
"migrate:dev": "sequelize db:migrate:undo && sequelize db:migrate",
"migrate:dev": "sequelize db:migrate",
"unmigrate:dev": "sequelize db:migrate:undo:all",
"seed:all": "sequelize db:seed:all",
"unseed:all": "sequelize db:seed:undo:all"
},
Expand Down
2 changes: 1 addition & 1 deletion server/config/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ module.exports = {
database: process.env.DB_NAME || 'elven_ah_dev',
host: process.env.DB_HOST || 'localhost',
port: process.env.DB_PORT || '5432',
operatorsAliases: false,
// operatorsAliases: false,
},
test: {
dialect: 'postgres',
Expand Down
2 changes: 1 addition & 1 deletion server/controllers/ArticleController.js
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ export default class ArticleController {
.catch(() => res.status(400).json({
status: 400,
success: false,
error: 'Article cannot be deleted'
error: 'Article can not be deleted'
}));
}
}
83 changes: 52 additions & 31 deletions server/controllers/CommentController.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import models from '../models';

const { Comment, User } = models;
const { Comment, User, Article } = models;

/**
* This class contains all the methods responsible for creating and querying
Expand All @@ -14,38 +14,29 @@ export default class CommentController {
* @param {object} res the response object
* @returns {object} the comment that was created.
*/
static createComment(req, res) {
const { username } = req.user;
static async createComment(req, res) {
const { id, username } = req.user;
const { body } = req.body;
const parentId = req.query.id === undefined ? null : req.query.id;
const slug = parentId === null ? req.params.slug : null;
Comment.create({
articleSlug: slug,
author: username,
parentId,
body,
}).then(newComment => res.status(201).json({
status: 'success',
message: 'Comment has been created',
comment: {
id: newComment.id,
parentId: newComment.parentId,
createdAt: new Date(newComment.createdAt).toLocaleString('en-GB', { hour12: true }),
updatedAt: new Date(newComment.updatedAt).toLocaleString('en-GB', { hour12: true }),
body: newComment.body,
article: newComment.articleSlug,
author: {
username: newComment.author,
bio: newComment.author.bio,
image: newComment.author.image,
following: 'true',
},
},
})).catch(() => {
res.status(400).json({
status: 'fail',
message: 'Unable to create comment.',
});
const { slug } = req.params;
const article = await CommentController.getArticleFromSlug(slug);
if (article !== undefined) {
return Comment.create({
articleId: article.id,
userId: id,
parentId,
body,
}).then(newComment => CommentController.commentResponse(res, newComment, slug, username))
.catch(() => {
res.status(400).json({
status: 'fail',
message: 'Unable to create comment, please try again.',
});
});
}
res.status(400).json({
status: 'fail',
message: 'Unable to create comment because article does not exist.',
});
}

Expand Down Expand Up @@ -204,4 +195,34 @@ export default class CommentController {
});
return result;
}

static getArticleFromSlug(slug) {
return new Promise((resolve, reject) => {
Article.findOne({
where: { slug },
attributes: [
'id', 'title', 'userId', 'slug', 'body',
'imageUrl', 'categoryId', 'createdAt', 'updatedAt'
],
})
.then(article => resolve(article))
.catch(err => reject(err));
});
}

static commentResponse(res, newComment, slug, username) {
return res.status(201).json({
status: 'success',
message: 'Comment has been created',
comment: {
id: newComment.id,
parentId: newComment.parentId,
createdAt: new Date(newComment.createdAt).toLocaleString('en-GB', { hour12: true }),
updatedAt: new Date(newComment.updatedAt).toLocaleString('en-GB', { hour12: true }),
body: newComment.body,
article: slug,
author: username,
},
});
}
}
2 changes: 1 addition & 1 deletion server/migrations/20180727115808-create-user.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ module.exports = {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
username: {
type: Sequelize.STRING,
allowNull: false,
primaryKey: true,
unique: true,
},
firstName: {
Expand Down
8 changes: 4 additions & 4 deletions server/migrations/20180806205551-create-article.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ module.exports = {
allowNull: false,
unique: true
},
author: {
type: Sequelize.STRING,
userId: {
type: Sequelize.INTEGER,
allowNull: false,
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
references: {
model: 'Users',
key: 'username',
as: 'author'
key: 'id',
as: 'userId'
},
},
categoryId: {
Expand Down
21 changes: 11 additions & 10 deletions server/migrations/20180806205745-create-comment.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,28 @@ module.exports = {
primaryKey: true,
type: Sequelize.INTEGER
},
articleSlug: {
type: Sequelize.STRING,
articleId: {
type: Sequelize.INTEGER,
allowNull: false,
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
references: {
model: 'Articles',
key: 'slug',
as: 'articleSlug'
key: 'id',
as: 'articleId'
},
},
author: {
type: Sequelize.STRING,
userId: {
type: Sequelize.INTEGER,
allowNull: false,
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
references: {
model: 'Users',
key: 'username',
as: 'author',
key: 'id',
as: 'userId'
},
onDelete: 'CASCADE',
onUpdate: 'CASCADE',

},
parentId: {
type: Sequelize.INTEGER,
Expand Down
10 changes: 6 additions & 4 deletions server/models/article.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,15 @@ export default (sequelize, DataTypes) => {
});
Article.associate = (models) => {
Article.belongsTo(models.User, {
foreignKey: 'author',
foreignKey: 'userId',
onDelete: 'CASCADE',
onUpdate: 'CASCADE'
});
Article.hasMany(models.Comment, {
foreignKey: 'articleSlug',
as: 'comments'
foreignKey: 'articleId',
as: 'comments',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
});
Article.hasMany(models.Tag, {
foreignKey: 'tagId',
Expand All @@ -38,7 +40,7 @@ export default (sequelize, DataTypes) => {
});
Article.belongsTo(models.Category, {
foreignKey: 'categoryId',
as: 'categories',
as: 'categories'
});
};
return Article;
Expand Down
1 change: 0 additions & 1 deletion server/models/category.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

export default (sequelize, DataTypes) => {
const Category = sequelize.define('Category', {
title: {
Expand Down
4 changes: 2 additions & 2 deletions server/models/comment.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export default (sequelize, DataTypes) => {
});
Comment.associate = (models) => {
Comment.belongsTo(models.Article, {
foreignKey: 'articleSlug',
foreignKey: 'articleId',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
});
Expand All @@ -22,7 +22,7 @@ export default (sequelize, DataTypes) => {
onUpdate: 'CASCADE',
});
Comment.belongsTo(models.User, {
foreignKey: 'author',
foreignKey: 'userId',
as: 'commenter',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
Expand Down
11 changes: 1 addition & 10 deletions server/models/rating.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,12 @@

export default (sequelize, DataTypes) => {
const Rating = sequelize.define('Rating', {
userId: {
type: DataTypes.INTEGER,
allowNull: false
},
articleId: {
type: DataTypes.INTEGER,
allowNull: false
},
value: {
type: DataTypes.STRING,
allowNull: false
},
}, {});
Rating.associate = (models) => {
Rating.BelongsTo(models.Article, {
Rating.belongsTo(models.Article, {
foreignKey: 'articleId',
onDelete: 'CASCADE',
onUpdate: 'CASCADE'
Expand Down
5 changes: 0 additions & 5 deletions server/models/tag.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@

export default (sequelize, DataTypes) => {
const Tag = sequelize.define('Tag', {
articleId: {
type: DataTypes.INTEGER,
allowNull: false
},
title: {
type: DataTypes.STRING,
allowNull: false
Expand Down
3 changes: 1 addition & 2 deletions server/models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ export default (sequelize, DataTypes) => {
type: DataTypes.STRING,
allowNull: false,
unique: true,
primaryKey: true,
},
email: {
type: DataTypes.STRING,
Expand Down Expand Up @@ -61,7 +60,7 @@ export default (sequelize, DataTypes) => {
as: 'articles',
});
User.hasMany(models.Comment, {
foreignKey: 'author',
foreignKey: 'userId',
as: 'comments',
});
};
Expand Down
1 change: 0 additions & 1 deletion server/seeders/20180808181558-demo-Article.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ module.exports = {
slug: 'arts-is-wonderful-120794ujhd',
userId: 1,
categoryId: 5,
author: 'unique',
createdAt: '2018-08-08 18:31:22.324',
updatedAt: '2018-08-08 18:31:22.324'
}
Expand Down
4 changes: 2 additions & 2 deletions server/seeders/20180812221146-demo comment.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
module.exports = {
up: queryInterface => queryInterface.bulkInsert('Comments', [
{
articleSlug: 'Arts-is-wonderful-120794ujhd',
author: 'unique',
articleId: 1,
userId: 2,
parentId: null,
body: 'Awesome Article, bro!!!!',
createdAt: '2018-08-10 18:31:22.324',
Expand Down
15 changes: 9 additions & 6 deletions server/tests/comment.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@ const { Article } = models;
chai.should();
chai.use(chaiHttp);
const user = {
id: 1,
id: 2,
username: 'unique',
email: 'testuser@test.com',
email: 'testseeder@test.com',
};
let token;
let validSlug;
let validId;

const comments = [
{
Expand Down Expand Up @@ -76,8 +77,9 @@ const comments = [
describe('Comment Tests', () => {
before((done) => {
token = JwtHelper.createToken({ user }, 3600);
Article.find({ attributes: ['slug'] }).then((article) => {
Article.findOne({ attributes: ['slug', 'id'] }).then((article) => {
validSlug = article.slug;
validId = article.id;
}).catch();
done();
});
Expand Down Expand Up @@ -115,12 +117,13 @@ describe('Comment Tests', () => {
.post(`/api/articles/${validSlug}/comments`)
.set('x-access-token', token)
.send({
articleSlug: validSlug,
author: user.username,
articleId: validId,
userId: user.id,
parentId: null,
body: 'I am a valid comment.',
})
.end((req, res) => {
console.log(`response is: ${JSON.stringify(res.body, null, 2)}=====`);
res.status.should.eql(201);
res.body.should.be.an('object').with.property('status').eql('success');
res.body.comment.should.have.property('article').include(validSlug);
Expand All @@ -137,7 +140,7 @@ describe('Comment Tests', () => {
.set('x-access-token', token)
.send({
articleSlug: validSlug,
author: user.username,
author: user.id,
parentId: null,
})
.end((req, res) => {
Expand Down

0 comments on commit bb2dead

Please sign in to comment.