Skip to content

Commit

Permalink
user should be able to update an article
Browse files Browse the repository at this point in the history
  • Loading branch information
mystere10 committed Jun 18, 2019
1 parent 0af167c commit 3450dc6
Show file tree
Hide file tree
Showing 12 changed files with 215 additions and 140 deletions.
26 changes: 14 additions & 12 deletions controllers/article.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ class Article {
*/
static async createArticle(req, res) {
const {
title, body, taglist, description
} = req.body;
title, body, taglist, description
} = req.body;
let { category } = req.body;
if (!category || category === '') {
category = 0;
Expand All @@ -50,13 +50,13 @@ class Article {
return helper.jsonResponse(res, 404, { error: 'Category not found' });
}
}

const image = req.file ? req.file.url : 'null';

if (!title) {
return res.status(400).json({ error: 'title can not be null' });
return res.status(400).json({ error: 'title can not be empty' });
}
if (!body) {
return res.status(400).json({ error: 'body can not be null' });
return res.status(400).json({ error: 'body can not be empty' });
}
const authorid = req.user;
const checkuser = await UserModel.checkuserExistance(authorid);
Expand Down Expand Up @@ -212,8 +212,8 @@ class Article {
static async updateArticle(req, res) {
const { slug } = req.params;
const {
title, body, taglist, description
} = req.body;
title, body, taglist, description
} = req.body;
let { category } = req.body;
if (!category || category === '') {
category = 0;
Expand All @@ -225,6 +225,7 @@ class Article {
return helper.jsonResponse(res, 404, { error: 'Category not found' });
}
}
const image = req.file ? req.file.url : 'null';
const authorid = req.user;
const searchArticle = await ArticleModel.findArticleSlug(authorid, slug);
if (!searchArticle) {
Expand All @@ -241,7 +242,8 @@ class Article {
description: description || searchArticle.description,
slug: newSlug.length === 8 ? searchArticle.slug : newSlug,
authorid,
taglist: !taglist ? taglist : searchArticle.taglist,
taglist: taglist.length !== 0 ? taglist : searchArticle.taglist,
image,
category
};
const updateArticle = await ArticleModel.updateFoundArticle(
Expand Down Expand Up @@ -272,8 +274,8 @@ class Article {
const { slug } = req.params;
const { user: userId } = req;
const {
comment, text, positionleft, positiontop
} = req.body;
comment, text, positionleft, positiontop
} = req.body;

const article = await ArticleModel.findOne({ where: { slug } });
if (!article) {
Expand Down Expand Up @@ -790,8 +792,8 @@ class Article {
}
const response = reported.map(
({
id, description, name, articleid, title, slug
}) => ({
id, description, name, articleid, title, slug
}) => ({
id,
category: name,
description,
Expand Down
23 changes: 13 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,26 @@ const swaggerDocument = YAML.load('./swagger.yaml');
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true,
}));
app.use((express.json()));
app.use(session({
secret: process.env.secretKey,
resave: false,
saveUninitialized: true,
}));
app.use(
bodyParser.urlencoded({
extended: true
})
);
app.use(express.json());
app.use(
session({
secret: process.env.secretKey,
resave: false,
saveUninitialized: true
})
);

app.use(passport.initialize());
app.use(passport.session());

app.use('/api', routes);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));


app.use(express.static(path.resolve(__dirname, 'view/')));

const port = process.env.PORT || 5000;
Expand Down
8 changes: 6 additions & 2 deletions middlewares/tokenValidation.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,13 @@ dotenv.config();
const { user: UserModel } = model;

const validateToken = async (req, res, next) => {
let token = req.headers['x-access-token'] || req.headers.authorization || req.headers['x-auth-token'];
let token = req.headers['x-access-token']
|| req.headers.authorization
|| req.headers['x-auth-token'];
if (!token) {
return res.status(401).send({ status: 401, error: 'Token is not Supplied' });
return res
.status(401)
.send({ status: 401, error: 'Token is not Supplied' });
}

if (token.startsWith('Bearer ')) {
Expand Down
54 changes: 28 additions & 26 deletions migrations/20190423150504-create-article-likes-and-dislikes.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,32 @@
/* eslint-disable indent */
/* eslint-disable no-unused-vars */
module.exports = {
up: (queryInterface, Sequelize) => queryInterface.createTable('ArticleLikesAndDislikes', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
user_id: {
type: Sequelize.INTEGER
},
article_id: {
type: Sequelize.INTEGER,
allowNull: false
},
like_value: {
type: Sequelize.STRING,
allowNull: false
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
}),
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
user_id: {
type: Sequelize.INTEGER
},
article_id: {
type: Sequelize.INTEGER,
allowNull: false
},
like_value: {
type: Sequelize.STRING,
allowNull: false
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
}),
down: (queryInterface, Sequelize) => queryInterface.dropTable('ArticleLikesAndDislikes')
};
41 changes: 22 additions & 19 deletions models/article.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ const ArticleModel = (sequelize, DataTypes) => {
type: DataTypes.STRING,
allowNull: false,
trim: true,
validate: { len: { args: 5 }, notEmpty: true }
validate: {
len: { args: 5, msg: 'Title can not be under 5 characters' },
notEmpty: true
}
},
body: {
type: DataTypes.TEXT,
Expand Down Expand Up @@ -43,15 +46,15 @@ const ArticleModel = (sequelize, DataTypes) => {
sequelizeTrasform(Article);
Article.createArticle = article => Article.create(article);
Article.getAll = userModel => Article.findAll({
include: [
{
model: userModel,
attributes: {
exclude: ['password']
}
include: [
{
model: userModel,
attributes: {
exclude: ['password']
}
]
});
}
]
});
Article.getOneArticle = slug => Article.findOne({ where: { slug } });
Article.findArticleSlug = (authorid, slug) => Article.findOne({ where: { authorid, slug } });
Article.deleteArticle = slug => Article.destroy({ where: { id: slug } });
Expand All @@ -75,17 +78,17 @@ const ArticleModel = (sequelize, DataTypes) => {
};
Article.addViewer = id => Article.increment('views', { by: 1, where: { id } });
Article.fetchLatest = userModel => Article.findAll({
order: [['createdAt', 'DESC']],
include: [
{
model: userModel,
attributes: {
exclude: ['password', 'email', 'role']
}
order: [['createdAt', 'DESC']],
include: [
{
model: userModel,
attributes: {
exclude: ['password', 'email', 'role']
}
],
limit: 6
});
}
],
limit: 6
});

Article.associate = (models) => {
Article.belongsTo(models.user, {
Expand Down
21 changes: 9 additions & 12 deletions models/user.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
/* eslint-disable arrow-parens */
/* eslint-disable indent */
/* eslint-disable max-len */
/* eslint-disable camelcase */
import helper from '../helpers/helper';

Expand Down Expand Up @@ -56,14 +59,11 @@ const UserModel = (Sequelize, DataTypes) => {
return result[0].dataValues;
};
User.checkEmail = email => User.findOne({ where: { email } });
User.resetpassword = (password, id) =>
User.update({ password }, { where: { id } });
User.resetpassword = (password, id) => User.update({ password }, { where: { id } });
User.checkUser = username => User.findOne({ where: { username } });
User.findUser = id => User.findOne({ where: { id } });
User.emailNotifications = (id, email_notifications) =>
User.update({ email_notifications }, { where: { id } });
User.checkuserExistance = authorid =>
User.findOne({
User.emailNotifications = (id, email_notifications) => User.update({ email_notifications }, { where: { id } });
User.checkuserExistance = authorid => User.findOne({
attributes: {
exclude: [
'id',
Expand Down Expand Up @@ -104,17 +104,14 @@ const UserModel = (Sequelize, DataTypes) => {
onDelete: 'CASCADE'
});
};
User.allUsers = async () =>
User.findAll({ attributes: ['username', 'bio', 'image', 'role'] });
User.singleUser = async username =>
User.findOne({
User.allUsers = async () => User.findAll({ attributes: ['username', 'bio', 'image', 'role'] });
User.singleUser = async username => User.findOne({
attributes: ['username', 'bio', 'image', 'role'],
where: { username }
});
User.verifyUser = id => User.findOne({ where: { id } });
User.checkEmail = email => User.findOne({ where: { email } });
User.resetpassword = (password, id) =>
User.update({ password }, { where: { id } });
User.resetpassword = (password, id) => User.update({ password }, { where: { id } });
User.checkUser = username => User.findOne({ where: { username } });
User.findUser = id => User.findOne({ where: { id } });
User.checkuser = authorid => User.findOne({ where: { id: authorid } });
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"body-parser": "^1.18.3",
"cloudinary": "^1.14.0",
"config": "^3.0.1",
"cors": "^2.8.4",
"cors": "^2.8.5",
"debug": "^4.1.1",
"dotenv": "^6.0.0",
"ejs": "^2.6.1",
Expand Down
7 changes: 6 additions & 1 deletion routes/api/articles.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,12 @@ router.delete(
AuthToken,
errorHandler(articleController.deleteArticle)
);
router.put('/:slug', AuthToken, errorHandler(articleController.updateArticle));
router.put(
'/:slug',
AuthToken,
imageUpload,
errorHandler(articleController.updateArticle)
);
router.get(
'/rating/articles',
errorHandler(articleController.articleRatingPagination)
Expand Down
Loading

0 comments on commit 3450dc6

Please sign in to comment.