Skip to content

Commit

Permalink
Merge branch 'develop' of github.com:andela/ah-92explorers-backend in…
Browse files Browse the repository at this point in the history
…to develop
  • Loading branch information
Herve Nkurikiyimfura authored and Herve Nkurikiyimfura committed Sep 6, 2019
2 parents 69d4966 + 0a1f874 commit fb88f98
Show file tree
Hide file tree
Showing 3 changed files with 113 additions and 39 deletions.
106 changes: 74 additions & 32 deletions controllers/article.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,19 +26,31 @@ class Article {
// @pagination
let page, limit;
if (Object.keys(req.query).length === 0) {
page = 1; limit = 10;
page = 1;
limit = 10;
} else if (req.query.limit === undefined) {
({ page } = req.query); limit = 10;
({ page } = req.query);
limit = 10;
} else ({ page, limit } = req.query);
// @retrieve articles
const allArticles = await articles.findAll({
order: [['createdAt', 'DESC']],
attributes: ['id', 'title', 'slug', 'description', 'body', 'tagList', 'image', 'createdAt', 'authorId'],
attributes: [
'id',
'title',
'slug',
'description',
'body',
'tagList',
'image',
'createdAt',
'authorId'
],
include: [
{
as: 'author',
model: users,
attributes: ['username', 'image'],
attributes: ['username', 'image']
},
{
as: 'comments',
Expand Down Expand Up @@ -77,7 +89,7 @@ class Article {
]
}
],
offset: ((parseInt(page, 10) - 1) * limit),
offset: (parseInt(page, 10) - 1) * limit,
limit
});
allArticles.forEach((item) => {
Expand Down Expand Up @@ -116,9 +128,9 @@ class Article {
title,
description,
body: he.encode(body),
tagList: (tagList ? tagList.split(',') : null),
tagList: tagList ? tagList.split(',') : null,
authorId: findUser.id,
image: (req.file ? req.file.url : null)
image: req.file ? req.file.url : null
});
const { slug, image } = article;
const user = await users.findOne({ where: { id: article.authorId } });
Expand All @@ -130,7 +142,7 @@ class Article {
body: he.decode(article.body),
tagList,
image,
author: { username, bio, image: user.image },
author: { username, bio, image: user.image }
};
const message = `${username} published new article`;
await notificationForFollower(article.authorId, message);
Expand All @@ -148,14 +160,12 @@ class Article {
* @returns {Object} return article
*/
static async getSingleArticle(req, res) {
const {
slug
} = req.params;
const { slug } = req.params;
try {
// @find an article which the slug
const article = await articles.findOne({
where: {
slug,
slug
},
include: [
{
Expand All @@ -178,13 +188,38 @@ class Article {
{
as: 'ratings',
model: ratings,
attributes: ['articleSlug', 'rating']
attributes: ['rating', 'createdAt', 'updatedAt'],
include: [
{
as: 'reviewer',
model: users,
attributes: ['username', 'image']
}
]
},
{
as: 'likes',
model: likes,
attributes: ['typeState', 'createdAt', 'updatedAt'],
include: [
{
as: 'liker',
model: users,
attributes: ['username', 'image']
}
]
}
]
});
const rating = await ratings.findAll({
where: {
articleSlug: article.slug
}
});

if (article) {
const {
title, description, tagList, image, author
title, description, tagList, image, author, comments
} = article;
const payload = {
time: accReadTime(article.body),
Expand All @@ -195,7 +230,9 @@ class Article {
tagList,
image,
author,
rating: article.ratings
comments: article.comments,
likes: article.likes,
ratings: rating
};
return res.status(200).json({ article: payload });
}
Expand All @@ -217,18 +254,21 @@ class Article {
} = req.body;
try {
// @update article
const updatedArticle = await articles.update({
title,
description,
body: he.encode(body),
tagList: (tagList ? tagList.split(',') : req.findArticle.tagList),
image: (req.file ? req.file.url : req.findArticle.image)
}, {
where: {
slug: req.params.slug
const updatedArticle = await articles.update(
{
title,
description,
body: he.encode(body),
tagList: tagList ? tagList.split(',') : req.findArticle.tagList,
image: req.file ? req.file.url : req.findArticle.image
},
individualHooks: true
});
{
where: {
slug: req.params.slug
},
individualHooks: true
}
);
const {
slug, authorId, image, createdAt, updatedAt
} = updatedArticle[1][0];
Expand All @@ -245,11 +285,11 @@ class Article {
authorId,
image,
createdAt,
updatedAt,
updatedAt
};
return res.status(200).json({
message: 'Article updated successfully',
article: payload,
article: payload
});
} catch (error) {
return res.status(500).json({ error: 'Failed to update the article, please try again' });
Expand Down Expand Up @@ -299,21 +339,23 @@ class Article {
if (process.env.NODE_ENV !== 'test') open(`https:www.facebook.com/sharer/sharer.php?u=${url}`);
res.status(200).json({
status: 200,
message: `Article shared to ${channel}`,
message: `Article shared to ${channel}`
});
break;
case 'twitter':
if (process.env.NODE_ENV !== 'test') { open(`https://twitter.com/intent/tweet?url=${url}`); }
if (process.env.NODE_ENV !== 'test') {
open(`https://twitter.com/intent/tweet?url=${url}`);
}
res.status(200).json({
status: 200,
message: `Article shared to ${channel}`,
message: `Article shared to ${channel}`
});
break;
case 'mail':
if (process.env.NODE_ENV !== 'test') open(`mailto:?subject=${slug}&body=${url}`);
res.status(200).json({
status: 200,
message: `Article shared to ${channel}`,
message: `Article shared to ${channel}`
});
break;
default:
Expand Down
45 changes: 38 additions & 7 deletions controllers/followers.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import models from '../models';

const { users, Follow } = models;
/**
* @param {class} --Followers controller
*/
* @param {class} --Followers controller
*/
class follower {
/**
* Users can follow each other
Expand Down Expand Up @@ -31,18 +31,47 @@ class follower {
userId: loggedinUser.id
});
return res.status(201).json({
message: `you are following ${checkUser.username}`,
message: `you are following ${checkUser.username}`
});
}
await Follow.destroy({ where: { userId: loggedinUser.id, followed: checkUser.id } });
return res.status(200).json({
message: `you unfollowed ${checkUser.username}`,
message: `you unfollowed ${checkUser.username}`
});
} catch (error) {
return res.status(500).json({ error: 'Something went wrong, please try again!' });
}
}

static async followed(req, res) {
try {
const { username } = req.params;
const checkUser = await users.findOne({ where: { username } });
const loggedinUser = await users.findOne({ where: { username: req.decoded.username } });
if (!checkUser) {
return res.status(404).json({ error: 'User does not exists!' });
}
if (checkUser.id === loggedinUser.id) {
return res.status(400).json({ error: 'You can not follow yourself' });
}
const following = await Follow.findOne({
where: { userId: loggedinUser.id, followed: checkUser.id }
});
if (following) {
return res.status(200).json({
message: 'following'
});
}
if (!following) {
return res.status(200).json({
message: 'follow'
});
}
} catch (error) {
return res.status(500).json({ error: 'Something went wrong, please try again!' });
}
}

/**
* Users can get his/her followers
* @param {object} req
Expand All @@ -55,12 +84,13 @@ class follower {
const followers = await Follow.findAll({
attributes: [],
where: { followed: loggedinUser.id },
include: [{ model: users, as: 'follower', attributes: ['username', 'image'] }]
include: { model: users, as: 'follower', attributes: ['username', 'image'] }
});
return followers.length
? res.status(200).json({
message: 'Followers',
followers
follower: followers.map(e => e.follower),
total: followers.length
})
: res.status(404).json({ error: "You don't have followers" });
} catch (error) {
Expand All @@ -85,7 +115,8 @@ class follower {
return following.length
? res.status(200).json({
message: 'Following',
following
following: following.map(e => e.following),
total: following.length
})
: res.status(404).json({ error: "You aren't following anyone" });
} catch (error) {
Expand Down
1 change: 1 addition & 0 deletions routes/api/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,7 @@ router.patch('/profiles', checkToken, uploadImage, Validations.validateProfile,
router.post('/:username/follow', checkToken, Follower.follow);
router.get('/followers', checkToken, Follower.followers);
router.get('/following', checkToken, Follower.following);
router.get('/:username/followed', checkToken, Follower.followed);

router.get('/users/reading-stats', checkToken, articleStats.getUserReadingStats);

Expand Down

0 comments on commit fb88f98

Please sign in to comment.