Skip to content

Commit

Permalink
[feature #167193975] CRUD - category of articles Added
Browse files Browse the repository at this point in the history
  • Loading branch information
UhiriweAudace committed Jul 10, 2019
1 parent 2c59539 commit c697cea
Show file tree
Hide file tree
Showing 17 changed files with 211 additions and 15 deletions.
115 changes: 115 additions & 0 deletions src/api/controllers/category.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import models from '../../sequelize/models';

const { Category, Article } = models;
/**
* @Author - Audace Uhiriwe
*/
class categoryController {
/**
* Admin - create a new category
* @param {object} req - Request.
* @param {object} res - Response.
* @returns {object} - returns a created article
*/
static async createCategory(req, res) {
// check if the category exists
const { categoryName } = req.body;
const categoryExists = await Category.findOne({ where: { categoryName } });
if (categoryExists) {
return res.status(400).send({ error: 'This category is already Exist!' });
}
const data = await Category.NewCategory(req.body);
return res.status(201).send({
message: `This category of ${categoryName} has been successfully added!`,
data
});
}

/**
* Admin - edit an existing category
* @param {object} req - Request.
* @param {object} res - Response.
* @returns {object} - returns an updated article
*/
static async editCategory(req, res) {
// check if the category exists
const { categoryName } = req.body;
const { id } = req.params;
const categoryExists = await Category.findAll({ where: { id } });
if (categoryExists[0].dataValues.categoryName === categoryName) {
return res.status(400).send({
error: 'This category is already exists, Nothing you changed!'
});
}
if (categoryExists === null) {
return res.status(404).send({ error: 'This category Not found!' });
}
const updateCategory = {
categoryName: categoryName || categoryExists[0].dataValues.categoryName
};
await Category.EditCategory(
updateCategory,
categoryExists[0].dataValues.id
);
return res.status(200).send({
message: `This category of ${categoryExists[0].dataValues.categoryName} has been successfully updated to ${categoryName}!`
});
}

/**
* Admin - delete an existing category
* @param {object} req - Request.
* @param {object} res - Response.
* @returns {object} - returns a message
*/
static async deleteCategory(req, res) {
const { id } = req.params;
// check if the category exists
const categoryExists = await Category.findOne({ where: { id } });
if (categoryExists === null) {
return res.status(404).send({ error: 'This category Not found!' });
}
await Category.destroy({ where: { id } });
return res.status(200).send({
message: 'This category has been successfully deleted!'
});
}

/**
* Admin - fetch all categories
* @param {object} req - Request.
* @param {object} res - Response.
* @returns {object} - returns an array of all categories
*/
static async getAllCategory(req, res) {
const categories = await Category.findAll();
if (categories === null) {
return res.status(200).send({ message: 'No Categories found, so far!' });
}
return res.status(200).send({
message: 'Here\'s all categories, so far!',
categories
});
}

/**
* Admin - fetch all articles related to a specific category
* @param {object} req - Request.
* @param {object} res - Response.
* @returns {object} - returns an array which contains all articles related to a specific category
*/
static async fetchAllArticles(req, res) {
const { categoryName } = req.params;
const category = await Category.findOne({ where: { categoryName } });
if (category === null) {
return res.status(200).send({ message: 'No Articles found with this Category, so far!' });
}
const articles = await Article.findAll({ where: { categoryName } });
return res.status(200).send({
message: 'Here\'s all articles related to that category, so far!',
articles
});
}
}

export default categoryController;
15 changes: 15 additions & 0 deletions src/api/routes/categoryRouter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Router } from 'express';
import CategoryController from '../controllers/category';
import Auth from '../../middleware/auth';

const categoryRouter = Router();
const { verifyToken, checkIsAdmin } = Auth;
// eslint-disable-next-line
const { createCategory,editCategory,deleteCategory,getAllCategory,fetchAllArticles } = CategoryController;

categoryRouter.post('/', verifyToken, checkIsAdmin, createCategory);
categoryRouter.put('/:id', verifyToken, checkIsAdmin, editCategory);
categoryRouter.delete('/:id', verifyToken, checkIsAdmin, deleteCategory);
categoryRouter.get('/', getAllCategory);
categoryRouter.get('/:categoryName/articles', fetchAllArticles);
export default categoryRouter;
2 changes: 2 additions & 0 deletions src/api/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import profilesRouter from './profilesRouter';
import articlesRouter from './articlesRouter';
import ratingsRouter from './ratingsRouter';
import bookmarkRouter from './bookmark';
import categoryRouter from './categoryRouter';

const api = express();

Expand All @@ -15,6 +16,7 @@ api.use('/profiles', profilesRouter);
api.use('/articles', articlesRouter);
api.use('/ratings', ratingsRouter);
api.use('/bookmarks', bookmarkRouter);
api.use('/category', categoryRouter);


export default api;
3 changes: 2 additions & 1 deletion src/helpers/articlesHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class ArticlesHelper {
*/
static async createNewArticle(req) {
const {
title, body, description, tagList
title, body, description, tagList, categoryName
} = req.body;
const { id } = req.user;
const newSlug = this.createSlug(title);
Expand All @@ -41,6 +41,7 @@ class ArticlesHelper {
authorId: parseInt(id, 10),
readtime,
views: 0,
categoryName: categoryName || 'other'
});
const userInfo = await this.getUserInfo(id);
const { username, bio, image } = userInfo;
Expand Down
6 changes: 5 additions & 1 deletion src/sequelize/migrations/20190613355309-create-article.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,11 @@ module.exports = {
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
},
categoryName: {
type: Sequelize.STRING,
allowNull: false
},
}),
down: (queryInterface, Sequelize) => queryInterface.dropTable('Articles')
};
26 changes: 26 additions & 0 deletions src/sequelize/migrations/20190710111019-create-category.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/* eslint-disable no-unused-vars */
module.exports = {
up: (queryInterface, Sequelize) => queryInterface.createTable('Categories', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
categoryName: {
type: Sequelize.STRING
},
articleId: {
type: Sequelize.INTEGER
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
}),
down: (queryInterface, Sequelize) => queryInterface.dropTable('Categories')
};
4 changes: 4 additions & 0 deletions src/sequelize/models/article.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ module.exports = (sequelize, DataTypes) => {
views: {
type: DataTypes.INTEGER
},
categoryName: {
type: DataTypes.STRING,
allowNull: false
},
},
{}
);
Expand Down
18 changes: 18 additions & 0 deletions src/sequelize/models/category.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/* eslint-disable no-unused-vars */
/* eslint-disable func-names */
module.exports = (sequelize, DataTypes) => {
const Category = sequelize.define('Category', {
categoryName: DataTypes.STRING,
articleId: DataTypes.INTEGER
}, {});

Category.NewCategory = data => Category.create({ categoryName: data.categoryName });
Category.EditCategory = (data, id) => Category.update(
{ categoryName: data.categoryName },
{ where: { id } }
);
Category.associate = function (models) {
// associations can be defined here
};
return Category;
};
2 changes: 1 addition & 1 deletion src/sequelize/seeders/20190618062925-test-user.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ module.exports = {
lastName: 'Audace',
username: 'Audace',
email: 'u.audace@gmail.com',
password: 'Uhiriwe1!',
password: '$2b$08$GCULzAkfmfB/fGyZrnfMSeFG.KdYasuBa2r7z1n.CUFy.KrdnOUdi',
bio: '',
image: '',
dateOfBirth: '12/12/1999',
Expand Down
9 changes: 6 additions & 3 deletions src/sequelize/seeders/20190620204605-articles-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ module.exports = {
createdAt: new Date(),
updatedAt: new Date(),
readtime: '2 min',
views: 0
views: 0,
categoryName: 'other'
},
{
slug: '73H99992',
Expand All @@ -26,7 +27,8 @@ module.exports = {
createdAt: new Date(),
updatedAt: new Date(),
readtime: '1min',
views: 0
views: 0,
categoryName: 'other'
},
{
slug: 'This_is_andela_2433546h34',
Expand All @@ -39,7 +41,8 @@ module.exports = {
createdAt: new Date(),
updatedAt: new Date(),
authorId: 4,
views: 0
views: 0,
categoryName: 'other'
}
]),

Expand Down
6 changes: 4 additions & 2 deletions test/articles.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,8 @@ describe('Like/Unlike Articles', () => {
tagList: ['reactjs', 'angularjs', 'expressjs'],
slug: 'lsug32344',
authorId: testUser.dataValues.id,
readtime: '1 min'
readtime: '1 min',
categoryName: 'other'
};

// create test article
Expand Down Expand Up @@ -464,7 +465,8 @@ describe('Block article', () => {
tagList: ['reactjs', 'angularjs', 'expressjs'],
slug: 'lsug38769',
authorId: testUser.dataValues.id,
readtime: '1 min'
readtime: '1 min',
categoryName: 'other'
});
});

Expand Down
3 changes: 2 additions & 1 deletion test/bookmark.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ describe('User should bookmark article', () => {
tagList: ['Tech', 'Kigali'],
authorId: newUser.id,
slug: 'slug',
readtime: 'Less than a minute'
readtime: 'Less than a minute',
categoryName: 'other'
};
newArticle = await Article.create(article);
});
Expand Down
6 changes: 4 additions & 2 deletions test/comments.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,8 @@ describe('Comments', () => {
image: '',
authorId: userOneId,
createdAt: new Date(),
updatedAt: new Date()
updatedAt: new Date(),
categoryName: 'other'
};
await models.Article.create(articleOne);

Expand All @@ -91,7 +92,8 @@ describe('Comments', () => {
image: '',
authorId: userOneId,
createdAt: new Date(),
updatedAt: new Date()
updatedAt: new Date(),
categoryName: 'other'
};
await models.Article.create(articleTwo);
});
Expand Down
3 changes: 2 additions & 1 deletion test/highlight.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ describe('Highlight the Article', () => {
tagList: ['Tech', 'Kigali'],
authorId: newUser.id,
slug: 'slyg',
readtime: '1 min'
readtime: '1 min',
categoryName: 'other'
};
newArticle = await Article.create(article);
});
Expand Down
2 changes: 1 addition & 1 deletion test/mock/articles.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ export default {
title: 'this is article one',
body: 'this is article is supposed to have two paragraph',
description: 'the paragraph one has many character than before',
tagList: 'reactjs , angularjs, expressjs'
tagList: 'reactjs , angularjs, expressjs',
},
updatedArticle: {
title: 'this is article two',
Expand Down
3 changes: 2 additions & 1 deletion test/ratings.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ describe('Rating Article', () => {
tagList: ['Tech', 'Kigali'],
authorId: newUser.id,
slug: 'slyg',
readtime: '1 min'
readtime: '1 min',
categoryName: 'other'
};
newArticle = await Article.create(article);
});
Expand Down
3 changes: 2 additions & 1 deletion test/ratingscarc.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ describe('Articles ratings', () => {
tagList: ['Tech', 'Kigali'],
authorId: newUser.id,
slug: 'slyg',
readtime: '1 min'
readtime: '1 min',
categoryName: 'other'
};
newArticle = await Article.create(article);
});
Expand Down

0 comments on commit c697cea

Please sign in to comment.