Skip to content

Commit

Permalink
Merge branch 'develop' of https://github.com/andela/artemis-ah-backend
Browse files Browse the repository at this point in the history
…into ch-add-is-bookmarked-property-165597004
  • Loading branch information
danprocoder committed Apr 29, 2019
2 parents fc5ffd8 + d2d4e63 commit 3fcf1b3
Show file tree
Hide file tree
Showing 3 changed files with 98 additions and 43 deletions.
82 changes: 57 additions & 25 deletions server/controllers/article.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint class-methods-use-this: "off" */
import slugify from 'slug';
import { validationResult } from 'express-validator/check';
import { Op } from 'sequelize';
import { HelperUtils } from '../utils';
import response, { validationErrors } from '../utils/response';
import db from '../database/models';
Expand Down Expand Up @@ -165,7 +166,10 @@ class ArticleController {
'Authors Haven <no-reply@authorshaven.com>',
notification.message,
notification.message,
articleNotificationMarkup(`${author.firstname} ${author.lastname}`, article.title, article.description, notification.url));
articleNotificationMarkup(`${author.firstname} ${author.lastname}`,
article.title,
article.description,
notification.url));
}

/**
Expand Down Expand Up @@ -255,7 +259,7 @@ class ArticleController {
'updatedAt'
],
order: [
['id', 'DESC'], // Fetch from the latest.
['id', 'DESC'] // Fetch from the latest.
]
};

Expand All @@ -265,17 +269,17 @@ class ArticleController {
}

// Total number of articles
const totalArticles = query.author ? (
await Article.count({
const totalArticles = query.author
? await Article.count({
where: { '$User.username$': query.author },
include: [
{
model: User,
attributes: ['username']
},
}
]
})
) : await Article.count();
: await Article.count();

Article.findAll(sequelizeOptions).then((articles) => {
response(res).success({
Expand Down Expand Up @@ -328,14 +332,17 @@ class ArticleController {
rating
});

const averageRating = HelperUtils.calcArticleRating(existingRatings.length,
req.article.rating,
this.rating);

await req.article.update({
rating: HelperUtils.calcArticleRating(existingRatings.length,
req.article.rating,
this.rating)
rating: averageRating
});

return response(res).success({
message: 'You have successfully rated this article'
message: 'You have successfully rated this article',
rating: averageRating
});
} catch (error) {
return response(res).serverError({
Expand Down Expand Up @@ -388,24 +395,31 @@ class ArticleController {
where: {
userId: id,
isRead: false,
'$Notification.type$': 'comment'
'$Notification.metaId$': req.article.id,
'$Notification.type$': {
[Op.or]: ['comment', 'article.published']
}
},
include: [{
model: Notification
}]
include: [
{
model: Notification
}
]
});

if (notify) {
await UserNotification.update({ isRead: true }, {
where: {
userId: id,
notificationId: notify.id,
}
});
await UserNotification.update({ isRead: true },
{
where: {
userId: id,
id: notify.id
}
});
}

const clap = await this.getClap(id, article.id);
let isBookmarked = false;
const rated = await this.checkUserRating(id, article.id);

// If user is logged in
if (req.user.id) {
Expand All @@ -424,7 +438,7 @@ class ArticleController {
});
}
}
response(res).success({ article: singleArticle[0], clap, isBookmarked });
response(res).success({ article: singleArticle[0], clap, rated, isBookmarked });
} catch (error) {
return response(res).serverError({ errors: { server: error } });
}
Expand Down Expand Up @@ -476,9 +490,7 @@ class ArticleController {
slug
},
attributes: {
exclude: [
'userId'
]
exclude: ['userId']
},
include: [
{
Expand All @@ -488,7 +500,7 @@ class ArticleController {
{
model: Tag,
attributes: ['name']
},
}
]
});
}
Expand All @@ -513,6 +525,26 @@ class ArticleController {

return isClapped.clap;
}

/**
* @describe get user clap
* @param {*} userId
* @param {*} articleId
* @returns {boolean} true or false
*/
async checkUserRating(userId, articleId) {
if (userId === undefined || userId === null) return false;
const rating = await Rating.findOne({
where: {
userId,
articleId
},
raw: true,
attributes: ['rating']
});

return Boolean(rating);
}
}

export default ArticleController;
37 changes: 22 additions & 15 deletions server/controllers/articleComment.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,14 @@ class Comment {
const comments = await ArticleComment.findAll({
where: {
articleId
}
},
order: [['id', 'DESC']],
include: [
{
model: User,
attributes: ['firstname', 'lastname', 'username', 'email', 'image']
}
]
});
return response(res).success({
message: 'Comments successfully retrieved',
Expand Down Expand Up @@ -88,12 +95,12 @@ class Comment {
metaId: userData.id,
type: 'comment',
title: article.title,
url: `/${slug}`,
url: `/${slug}`
});

await UserNotification.create({
userId: userData.id,
notificationId: notification.dataValues.id,
notificationId: notification.dataValues.id
});
}
});
Expand Down Expand Up @@ -126,12 +133,13 @@ class Comment {
});
}

const articleUpdate = await ArticleComment.update({ comment }, {
where: {
id
},
returning: true
});
const articleUpdate = await ArticleComment.update({ comment },
{
where: {
id
},
returning: true
});
const userComment = articleUpdate[1][0];
return response(res).success({
message: 'Comment updated successfully',
Expand Down Expand Up @@ -187,7 +195,8 @@ class Comment {
comment,
highlighted,
index,
userId });
userId
});
return response(res).created({
message: 'Comment created successfully',
userComment
Expand Down Expand Up @@ -221,19 +230,17 @@ class Comment {
const { user } = req;
// If user is not an admin AND is also not the persone that created the comment.
if (user.id !== comment.userId && !user.isAdmin) {
return response(res).unauthorized('You don\'t have permission to view this');
return response(res).unauthorized("You don't have permission to view this");
}
comment.userId = undefined; // user ID should not show in response.

// Get comment history
const dbHistory = await CommentEditHistory.findAll({
where: {
commentId,
commentId
},
attributes: [['previousComment', 'comment'], 'createdAt'],
order: [
['id', 'DESC']
]
order: [['id', 'DESC']]
});

let original, history;
Expand Down
22 changes: 19 additions & 3 deletions server/controllers/bookmark.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import db from '../database/models';
import { response } from '../utils';
import { response, HelperUtils } from '../utils';

const { Bookmark, Article, User } = db;
const { Bookmark, Article, User, Tag } = db;

/**
* @description Controller to bookmark articles
Expand Down Expand Up @@ -103,9 +103,18 @@ export default class BookmarkController {
'title',
'description',
'body',
'tagId',
'coverUrl',
'rating',
'totalClaps',
'createdAt',
'updatedAt']
'updatedAt'],
include: [{
model: Tag,
attributes: [
'name'
]
}]
}]
});

Expand All @@ -121,19 +130,26 @@ export default class BookmarkController {
title,
description,
body,
rating,
coverUrl,
totalClaps,
createdAt,
updatedAt
} = data.Article;
const { articleAuthor } = data;
const readTime = HelperUtils.estimateReadingTime(body);

return {
articleAuthor,
slug,
userId,
title,
rating,
coverUrl,
readTime,
description,
body,
Tag: data.Article.Tag,
totalClaps,
createdAt,
updatedAt
Expand Down

0 comments on commit 3fcf1b3

Please sign in to comment.