Skip to content

Commit

Permalink
Merge 8d63b2f into ef98bac
Browse files Browse the repository at this point in the history
  • Loading branch information
IsaiahRn committed Jul 25, 2019
2 parents ef98bac + 8d63b2f commit d9dbfba
Show file tree
Hide file tree
Showing 9 changed files with 384 additions and 2 deletions.
103 changes: 103 additions & 0 deletions controllers/followers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import models from '../models';

const { users, Follow } = models;
/**
* @param {class} --Followers controller
*/
class follower {
/**
* Users can follow each other
* @param {object} req
* @param {object} res
* @returns {object} res message
*/

static async follow(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) {
await Follow.create({
followed: checkUser.id,
userId: loggedinUser.id
});
return res.status(201).json({
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}`,
});
} catch (error) {
return res.status(500).json({ error: 'Something went wrong, please try again!' });
}
}

/**
* Users can get his/her followers
* @param {object} req
* @param {object} res
* @returns {object} res message
*/

static async followers(req, res) {
try {
const loggedinUser = await users.findOne({ where: { username: req.decoded.username } });
const followers = await Follow.findAll({
attributes: [],
where: { followed: loggedinUser.id },
include: [{ model: users, as: 'User', attributes: ['username', 'image'] }]
});
return followers.length
? res.status(200).json({
message: 'Followers',
followers
})
: res.status(404).json({ error: "You don't have followers" });
} catch (error) {
return res.status(500).json({ error: 'Failed to fetch followers, please try again!' });
}
}

/**
* Users can get his followings
* @param {object} req
* @param {object} res
* @returns {object} res message
*/

static async following(req, res) {
try {
const loggedinUser = await users.findOne({ where: { username: req.decoded.username } });
const following = await Follow.findAll({
attributes: [],
where: { userId: loggedinUser.id },
include: [{ model: users, as: 'User', attributes: ['username', 'image'] }]
});
return following.length
? res.status(200).json({
message: 'Following',
following
})
: res.status(404).json({ error: "You aren't following anyone" });
} catch (error) {
return res.status(500).json({ error: 'Failed to fetch following, please try again!' });
}
}
}
export default follower;
2 changes: 1 addition & 1 deletion middlewares/checkToken.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const checkToken = async (req, res, next) => {
const tokenFound = await client.getAsync(token);
switch (true) {
case token === undefined:
return res.status(401).json({
return res.json({
error: 'unauthorised to use this resource, please signup/login',
});
case tokenFound === 'Blacklisted':
Expand Down
4 changes: 4 additions & 0 deletions migrations/20190704173059-createTableUsers.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ export const up = (queryInterface, Sequelize) => queryInterface.createTable('use
type: Sequelize.INTEGER,
defaultValue: '0'
},
timestamps: {
allowNull: true,
type: Sequelize.DATE
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
Expand Down
37 changes: 37 additions & 0 deletions migrations/20190718183039-create-follower.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
module.exports = {
up: (queryInterface, Sequelize) => queryInterface.createTable(
'Follow', {
userId: {
type: Sequelize.UUID,
allowNull: false,
primaryKey: true,
onUpdate: 'CASCADE',
onDelete: 'CASCADE',
references: {
model: 'users',
key: 'id'
}
},
followed: {
type: Sequelize.UUID,
allowNull: false,
primaryKey: true,
onUpdate: 'CASCADE',
onDelete: 'CASCADE',
references: {
model: 'users',
key: 'id'
}
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
}
),
down: queryInterface => queryInterface.dropTable('Follow')
};
45 changes: 45 additions & 0 deletions models/followers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
export default (sequelize, DataTypes) => {
const Follow = sequelize.define(
'Follow', {
userId: {
type: DataTypes.UUID,
allowNull: false,
primaryKey: true,
references: {
model: 'users',
key: 'id'
},
followed: {
type: DataTypes.UUID,
allowNull: false,
primaryKey: true,
references: {
model: 'users',
key: 'id'
}
},
}
},
{
timestamps: true,
tableName: 'Follow'
}
);
Follow.associate = (models) => {
Follow.belongsTo(models.users, {
foreignKey: 'userId',
as: 'follower',
targetkey: 'id',
onUpdate: 'CASCADE',
onDelete: 'CASCADE'
});
Follow.belongsTo(models.users, {
foreignKey: 'followed',
as: 'User',
targetkey: 'id',
onUpdate: 'CASCADE',
onDelete: 'CASCADE'
});
};
return Follow;
};
3 changes: 3 additions & 0 deletions models/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ export default (sequelize, DataTypes) => {
users.hasMany(models.articles, { as: 'author', foreignKey: 'authorId' });
users.hasMany(models.ratings, { foreignKey: 'userId' });
users.hasMany(models.likes, { foreignKey: 'userId' });
users.hasMany(models.articles, { foreignKey: 'authorId', allowNull: false });
users.hasMany(models.comments, { foreignKey: 'authorId', allowNull: false });
users.hasMany(models.Follow, { as: 'User', foreignKey: 'followed' });
};
return users;
};
6 changes: 6 additions & 0 deletions routes/api/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,13 @@ import {
import Validations from '../../middlewares/validations/authValidations';
import Profile from '../../controllers/profile';
import uploadImage from '../../middlewares/imageUpload';
import Follower from '../../controllers/followers';
import { checkToken } from '../../middlewares';
import socialAuth from '../../controllers/socialAuth';
import resetPasswordController from '../../controllers/resetPassword';

// const follower = new Follower();

const router = express.Router();
/**
* @swagger
Expand Down Expand Up @@ -275,5 +278,8 @@ router.get('/profiles/:username', checkToken, Profile.getProfile);
* description: "User does not exists!"
*/
router.patch('/profiles', checkToken, uploadImage, Validations.validateProfile, Profile.updateProfile);
router.post('/:username/follow', checkToken, Follower.follow);
router.get('/followers', checkToken, Follower.followers);
router.get('/following', checkToken, Follower.following);

export default router;
Loading

0 comments on commit d9dbfba

Please sign in to comment.