Skip to content

Commit

Permalink
bg(followers): refactoring followers
Browse files Browse the repository at this point in the history
  • Loading branch information
Patrick Ngabonziza committed Jul 30, 2019
1 parent cfedf00 commit 9f6d8ba
Show file tree
Hide file tree
Showing 14 changed files with 172 additions and 143 deletions.
87 changes: 55 additions & 32 deletions src/controllers/followers.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import models from '../models';
import { follow, getUser, checkUser, unfollowUser } from './helpers/followersHelper';

const { User, Follow } = models;
/**
Expand All @@ -14,19 +15,20 @@ export default class FollowerController {
static async followUser(req, res) {
try {
const { username } = req.params;
const checkUser = await User.findOne({ where: { username: String(username) } });
if (!checkUser) return res.status(404).json({ error: 'Username not found' });
if (checkUser.id === req.user.id) return res.status(400).json({ error: 'You can not follow yourself' });
const findUser = await getUser(username);
if (!findUser) return res.status(404).json({ error: 'Username not found' });
if (findUser.id === req.user.id) return res.status(400).json({ error: 'You can not follow yourself' });

const isUserFollowed = await Follow.findOne({ where: { followed: checkUser.id } });
if (isUserFollowed) return res.status(409).json(`Already following ${username}`);

await Follow.create({ followed: checkUser.id,
userId: req.user.id });

return res.status(201).json({ message: `Following ${checkUser.username}` });
const followedUser = await checkUser(findUser.id);
if (followedUser) return res.status(409).json({ error: `Already following ${findUser.username}` });
await follow(findUser.id, req.user.id);
return res.status(201).json({ message: `Following ${findUser.username}`,
username: findUser.username,
bio: findUser.bio,
image: findUser.image,
following: findUser.following });
} catch (error) {
return res.status(500).json(error.message);
return res.status(500).json({ error: 'server error' });
}
}

Expand All @@ -35,17 +37,22 @@ export default class FollowerController {
* @param {Object} res
* @returns {Object} Unfollow user
*/
static async unFollowUser(req, res) {
const [username, user] = [req.params.username, req.user];
const checkUser = await User.findOne({ where: { username: String(username) } });
if (!checkUser) return res.status(404).json({ error: 'Username not found' });
const unFollowed = Object.keys(checkUser).length
? await Follow.destroy({ where: { userId: user.id, followed: checkUser.id } }) : null;

if (unFollowed && unFollowed.errors) return res.status(500).json({ errors: 'Server error! Something went wrong!' });
return unFollowed
? res.status(200).json({ message: `Unfollowed ${username}` })
: res.status(404).json({ errors: { follow: `You are not following "${username}"` } });
static async unfollowUser(req, res) {
const { username } = req.params;
const userId = req.user.id;
try {
const findUser = await getUser(username);
if (!findUser) return res.status(404).json({ error: 'Username not found' });
const followedUser = await checkUser(findUser.id);
return followedUser ? await unfollowUser(userId, findUser.id) && res.status(200).json({ message: `Unfollowed ${findUser.username}`,
username: findUser.username,
bio: findUser.bio,
image: findUser.image,
following: findUser.following })
: res.status(404).json({ errors: { follow: `Not following "${findUser.username}"` } });
} catch (error) {
return res.status(500).json({ error: 'Server error' });
}
}

/**
Expand All @@ -54,11 +61,19 @@ export default class FollowerController {
* @returns {Object} List of followers
*/
static async followers(req, res) {
const followers = await Follow.findAll({ where: { followed: req.user.id } });
return followers.length
? res.status(200).json({ message: 'Followers',
followers })
: res.status(404).json({ errors: { follows: "You don't have followers" } });
try {
const followers = await Follow.findAll({ where: { followed: req.user.id },
include: [{ model: User,
as: 'follower',
attributes: ['id', 'username', 'email',
'image', 'bio', 'following'] }] });
return followers.length
? res.status(200).json({ message: 'Followers',
followers })
: res.status(404).json({ error: { follows: 'No followers found!' } });
} catch (error) {
return res.status(500).json({ error: 'Server error' });
}
}

/**
Expand All @@ -67,10 +82,18 @@ export default class FollowerController {
* @returns {Object} List of following users
*/
static async following(req, res) {
const following = await Follow.findAll({ where: { userId: req.user.id } });
return following.length
? res.status(200).json({ message: 'Following',
following })
: res.status(404).json({ errors: { follows: "You don't follow anyone" } });
try {
const following = await Follow.findAll({ where: { userId: req.user.id },
include: [{ model: User,
as: 'followedUser',
attributes: ['id', 'username', 'email',
'image', 'bio', 'following'] }] });
return following.length
? res.status(200).json({ message: 'Following',
following })
: res.status(404).json({ error: { follows: "You don't follow anyone" } });
} catch (error) {
return res.status(500).json({ error: 'Server error' });
}
}
}
2 changes: 1 addition & 1 deletion src/controllers/helpers/checkRole.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ import model from '../../models';

const { Permissions } = model;

const checkAction = async (role, actions) => (Permissions.findOne({ where: { role, actions } }));
const checkAction = (role, actions) => (Permissions.findOne({ where: { role, actions } }));

export default checkAction;
6 changes: 2 additions & 4 deletions src/controllers/helpers/findArticle.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ import model from '../../models';

const { Articles } = model;

const findArticle = async (ArticleId) => {
const oneArticle = await Articles.findOne({ where: { id: ArticleId } });
return oneArticle;
};
const findArticle = ArticleId => Articles.findOne({ where: { id: ArticleId } });


export default findArticle;
5 changes: 1 addition & 4 deletions src/controllers/helpers/findComment.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@ import model from '../../models';

const { Comments } = model;

const findComment = async (commentId) => {
const oneArticle = await Comments.findOne({ where: { id: commentId } });
return oneArticle;
};
const findComment = commentId => Comments.findOne({ where: { id: commentId } });

export default findComment;
15 changes: 15 additions & 0 deletions src/controllers/helpers/followersHelper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/* eslint-disable require-jsdoc */

import models from '../../models';

const { User, Follow } = models;

const follow = (followed, userId) => Follow.create({ followed, userId });

const getUser = username => User.findOne({ where: { username } });

const checkUser = followed => Follow.findOne({ where: { followed } });

const unfollowUser = (userId, followed) => Follow.destroy({ where: { userId, followed } });

export { follow, getUser, checkUser, unfollowUser };
6 changes: 2 additions & 4 deletions src/controllers/helpers/rateHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@ import model from '../../models';

const { Rating, Articles } = model;

const findArticle = async (articleId) => {
const article = await Articles.findOne({ where: { id: articleId } });
return article;
};
const findArticle = articleId => Articles.findOne({ where: { id: articleId } });

const findRatings = async (userId, articleId) => {
const rating = await Rating.findOne({ where: { reviewerId: userId, articleId } });
return rating;
Expand Down
4 changes: 0 additions & 4 deletions src/controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,6 @@ export default class UserController {
static async verifyUser(req, res) {
try {
const decode = await decodeToken(req.params.userToken);
if (!decode.email || decode.verified) {
return (!decode.email && res.status(409).json({ error: `Email:${decode.email} does not exist in the database` }))
|| (decode.verified && res.status(409).json({ error: 'Your account is already verified' }));
}
await User.update({ verified: true }, { where: { email: decode.email } });
return res.status(200).json({ message: 'Your account is now verified you can login with your email', });
} catch (error) {
Expand Down
39 changes: 0 additions & 39 deletions src/migrations/20190624-create-userschema.js

This file was deleted.

4 changes: 2 additions & 2 deletions src/routes/followRoute.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ const { verifyToken } = Auth;

const router = express.Router();

router.patch('/:username/follow', verifyToken, Followers.followUser);
router.patch('/:username/unfollow', verifyToken, Followers.unFollowUser);
router.post('/:username/follow', verifyToken, Followers.followUser);
router.delete('/:username/follow', verifyToken, Followers.unfollowUser);
router.get('/followers', verifyToken, Followers.followers);
router.get('/following', verifyToken, Followers.following);
export default router;
2 changes: 1 addition & 1 deletion src/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ router.use('/api', likeAndDislike);
// social route for test
router.use('/api/social', socialRoute);
router.use('/api/articles', commentRoute);
router.use('/api/users', followerRoute);
router.use('/api/profiles', followerRoute);
router.use('/api', socialAPIRoute);
router.use('/api', readerStatsRoute);
router.use('/api', reportArticle);
Expand Down
1 change: 1 addition & 0 deletions src/test/articlesTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const { generateToken } = Tokenizer;
chai.use(chaiHttp);
chai.should();

// eslint-disable-next-line import/no-mutable-exports
let userObject, articleObject, testUser, testArticle, tokenGen, tokens;

describe('Article', () => {
Expand Down
55 changes: 32 additions & 23 deletions src/test/follower.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,21 +29,20 @@ describe('FOLLOW', () => {
tokenGen2 = await generateToken({ id: newUser1.id });
});

it('Users should be able to follow each other', (done) => {
it('User1 should be able to follow the User2', (done) => {
const username = 'Joseph';
chai.request(app)
.patch(`/api/users/${username}/follow`)
.post(`/api/profiles/${username}/follow`)
.set('token', tokenGen2)
.end((err, res) => {
res.should.have.status(201);
done();
});
});

it('Users should be able to follow each other', (done) => {
it('User2 should be able to follow user1', (done) => {
const username = 'FollowMan';
chai.request(app)
.patch(`/api/users/${username}/follow`)
.post(`/api/profiles/${username}/follow`)
.set('token', tokenGen1)
.end((err, res) => {
res.should.have.status(201);
Expand Down Expand Up @@ -132,7 +131,7 @@ describe('FOLLOW', () => {
it('Should return following users', (done) => {
chai
.request(app)
.get('/api/users/following')
.get('/api/profiles/following')
.set('token', tokenGen1)
.end((err, res) => {
res.should.have.status(200);
Expand All @@ -143,28 +142,49 @@ describe('FOLLOW', () => {
const username = 'Kagabo';
chai
.request(app)
.patch(`/api/users/${username}/follow`)
.post(`/api/profiles/${username}/follow`)
.set('token', ' ')
.end((err, res) => {
res.should.have.status(401);
done();
});
});
it('Should return followers', (done) => {
chai
.request(app)
.get('/api/profiles/followers')
.set('token', tokenGen2)
.end((err, res) => {
res.should.have.status(200);
done();
});
});
it('Fail to return followers when they dont exist', (done) => {
chai
.request(app)
.get('/api/profiles/followers')
.set('token', tokenGen1)
.end((err, res) => {
res.should.have.status(404);
done();
});
});


it('User should be able to unfollow user', (done) => {
const username = 'FollowMan';
chai.request(app)
.patch(`/api/users/${username}/unfollow`)
.delete(`/api/profiles/${username}/follow`)
.set('token', tokenGen1)
.end((err, res) => {
res.should.have.status(200);
done();
});
});
it('Fail to unfollow user that you dont follow', (done) => {
const username = 'Joseph';
const username = 'Kagabo';
chai.request(app)
.patch(`/api/users/${username}/unfollow`)
.delete(`/api/profiles/${username}/follow`)
.set('token', tokenGen1)
.end((err, res) => {
res.should.have.status(404);
Expand All @@ -175,28 +195,17 @@ describe('FOLLOW', () => {
const username = 'Joseph';
chai
.request(app)
.patch(`/api/users/${username}/unfollow`)
.delete(`/api/profiles/${username}/follow`)
.set('token', ' ')
.end((err, res) => {
res.should.have.status(401);
done();
});
});
it('Fail to return followers when they dont exist', (done) => {
chai
.request(app)
.get('/api/users/followers')
.set('token', tokenGen1)
.end((err, res) => {
res.should.have.status(404);
done();
});
});

it('Should not return following users', (done) => {
chai
.request(app)
.get('/api/users/following')
.get('/api/profiles/following')
.set('token', tokenGen1)
.end((err, res) => {
res.should.have.status(404);
Expand Down
1 change: 1 addition & 0 deletions src/test/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ describe('users', () => {
it('should verify a user', (done) => {
chai.request(app)
.patch(`/api/users/verification/${tokenGen}`)
.send({ verified: true })
.end((req, res) => {
res.should.have.status(200);
res.body.should.have.property('message').eql('Your account is now verified you can login with your email');
Expand Down
Loading

0 comments on commit 9f6d8ba

Please sign in to comment.