Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added votes functionality #57

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/controllers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const postsController = require('./posts.controller');
const tagsController = require('./tags.controller');
const usersController = require('./users.controller');
const authController = require('./auth.controller');
const votesController = require('./votes.controller')

module.exports = {
answersController,
Expand All @@ -12,4 +13,5 @@ module.exports = {
tagsController,
usersController,
authController,
votesController
};
90 changes: 90 additions & 0 deletions src/controllers/votes.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
const { validationResult } = require('express-validator');
const { responseHandler, asyncHandler } = require('../helpers');
const { votesService } = require('../services');

exports.getUserVote = asyncHandler(async (req, res) => {
try {
const { id } = req.user;
const { target_type, target_id } = req.params;
await votesService.retrieve(target_type, target_id, id, (err, data) => {
if (err) {
console.log(err);
return res.status(err.code).json(err);
}
// console.log(data.vote_score);
return res.status(data.code).json(data);
});
} catch (err) {
console.log(err);
return res
.status(500)
.json(responseHandler(false, 500, 'Server Error', null));
}
})

exports.getAllVotes = asyncHandler(async (req, res) => {
try {
const { target_type, target_id } = req.params;
await votesService.retrieveAll(target_type, target_id, (err, data) => {
if (err) {
console.log(err);
return res.status(err.code).json(err);
}
return res.status(data.code).json(data);
});
} catch (err) {
console.log("err");
return res
.status(500)
.json(responseHandler(false, 500, 'Server Error', null));
}
})

exports.addVote = asyncHandler(async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res
.status(400)
.json(responseHandler(false, 400, errors.array()[0].msg, null));
}
try {
const { id } = req.user;
const { target_type, target_id } = req.params;
const { score } = req.body;

await votesService.add(target_type, target_id, id, score, (err, data) => {
if (err) {
console.log(err);
return res.status(err.code).json(err);
}
return res.status(data.code).json(data);
});
} catch (err) {
console.log(err);
return res
.status(500)
.json(responseHandler(false, 500, 'Server Error', null));
}
})

exports.deleteVote = asyncHandler(async (req, res) => {
try {
const { id } = req.user;
const {target_type, target_id } = req.params;

await votesService.remove(target_type, target_id, id, (err, data) => {
if (err) {
console.log(err);
return res.status(err.code).json(err);
}
return res.status(data.code).json(data);
});
} catch (err) {
console.log(err);
return res
.status(500)
.json(responseHandler(false, 500, 'Server Error', null));
}
})


32 changes: 31 additions & 1 deletion src/models/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const { TagsModel } = require('./tags.model');
const { PostTagModel } = require('./posttag.model');
const { AnswersModel } = require('./answers.model');
const { CommentsModel } = require('./comments.model');
const {VotesModel} = require('./votes.model')

UsersModel.hasMany(PostsModel, {
foreignKey: { name: 'user_id', allowNull: false },
Expand All @@ -30,6 +31,34 @@ PostsModel.hasMany(AnswersModel, {
});
AnswersModel.belongsTo(PostsModel);

// New association for VotesModel
UsersModel.hasMany(VotesModel, {
foreignKey: { name: 'user_id', allowNull: false },
});
VotesModel.belongsTo(UsersModel);

PostsModel.hasMany(VotesModel, {
foreignKey: { name: 'target_id', allowNull: false },
scope: {
target_type: 'post', // Specify the target type for posts
},
});
VotesModel.belongsTo(PostsModel, {
foreignKey: { name: 'target_id', allowNull: false },
as: 'post', // Alias for the association
});

AnswersModel.hasMany(VotesModel, {
foreignKey: { name: 'target_id', allowNull: false },
scope: {
target_type: 'answer', // Specify the target type for answers
},
});
VotesModel.belongsTo(AnswersModel, {
foreignKey: { name: 'target_id', allowNull: false },
as: 'answer', // Alias for the association
});

PostsModel.belongsToMany(TagsModel, { through: PostTagModel, foreignKey: { name: 'post_id', allowNull: false } });
TagsModel.belongsToMany(PostsModel, { through: PostTagModel, foreignKey: { name: 'tag_id', allowNull: false } });

Expand All @@ -40,4 +69,5 @@ module.exports = {
PostTagModel,
AnswersModel,
CommentsModel,
};
VotesModel
};
35 changes: 35 additions & 0 deletions src/models/votes.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const { DataTypes } = require('sequelize');
const db = require('../config/db.config');

const VotesModel = db.define('votes', {
target_type: {
type: DataTypes.STRING(10),
allowNull: false,
},
target_id: {
type: DataTypes.UUID,
allowNull: false,
},
user_id: {
type: DataTypes.UUID,
allowNull: false,
},
vote_score: {
type: DataTypes.INTEGER,
allowNull: false,
},
}, {
db,
tableName: 'votes',
underscored: true,
timestamps: false,
indexes: [
{
unique: true,
fields: ['target_type', 'target_id', 'user_id'],
},
],
});

module.exports = { VotesModel };

17 changes: 7 additions & 10 deletions src/repositories/answers.repository.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,14 @@ exports.create = async (newAnswer, result) => {
result(responseHandler(false, 500, 'Some error occurred while adding the answer.', null), null);
});
};

exports.remove = async (id, result) => {
await AnswersModel.destroy({
where: { id },
})
.then(() => {
result(null, responseHandler(true, 200, 'Answer Removed', null));
})

exports.remove = async (id, t) => {
await AnswersModel
.destroy({ where: { id } }, { transaction: t })
.then(() => ({ status: true, message: 'Answer Removed' }))
.catch((error) => {
console.log(error.message);
result(responseHandler(false, 404, 'This answer doesn\'t exists', null), null);
console.log(error);
throw new Error(`Answer Delete Operation Failed: ${error}`);
});
};

Expand Down
2 changes: 2 additions & 0 deletions src/repositories/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const AnswersRepository = require('./answers.repository');
const CommentsRepository = require('./comments.repository');
const TagsRepository = require('./tags.repository');
const PostTagRepository = require('./posttag.repository');
const VotesRepository = require('./votes.repositories');

module.exports = {
UsersRepository,
Expand All @@ -12,4 +13,5 @@ module.exports = {
CommentsRepository,
TagsRepository,
PostTagRepository,
VotesRepository
};
101 changes: 101 additions & 0 deletions src/repositories/votes.repositories.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
const { VotesModel } = require('../models');
const { responseHandler } = require('../helpers');

exports.addVote = async (targetType, targetId, userId, newScore, result) => {
try {
const existingVote = await VotesModel.findOne({
where: { target_type: targetType, target_id: targetId, user_id: userId },
});

if (existingVote) {
await VotesModel.update(
{ vote_score: newScore },
{
where: { target_type: targetType, target_id: targetId, user_id: userId },
}
);
} else {
await VotesModel.create({
target_type: targetType,
target_id: targetId,
user_id: userId,
vote_score: newScore
});
}

result(responseHandler(true, 200, 'Vote added/updated successfully', null), null);
} catch (error) {
console.error(error);
result(responseHandler(false, 500, 'Failed to add/update vote', null), null);
}
};

exports.remove = async (targetType, targetId, userId, result) => {
try {
const deletedCount = await VotesModel.destroy({
where: { target_type: targetType, target_id: targetId, user_id: userId },
});

if (deletedCount === 0) {
// If no vote was deleted, you can consider returning a response
// indicating that there was no vote to delete.
result(responseHandler(true, 200, 'No vote found to delete', null), null);
return;
}

result(responseHandler(true, 200, 'Vote deleted successfully', null), null);
} catch (error) {
console.log(error);
result(responseHandler(false, 500, 'Failed to delete vote', null), null);
}
};


exports.retrieveVote = async (targetType, targetId, userId, result) => {
try {
const vote = await VotesModel.findOne({
where: { target_type: targetType, target_id: targetId, user_id: userId },
});

if (vote === null) {
// If there's no matching vote, you can consider returning a response
// indicating that the user hasn't voted on this target.
result(responseHandler(true, 200, 'User has not voted on this target', null), null);
return;
}

result(responseHandler(true, 200, 'Vote retrieved successfully', {votes : vote.vote_score}), vote);
} catch (error) {
console.log(error);
result(responseHandler(false, 500, 'Failed to get vote', null), null);
}
};


exports.retrieveVoteScore = async (targetType, targetId, result) => {
try {
console.log(targetId, targetType);
const voteScore = await VotesModel.sum('vote_score', {
where: { target_type: targetType, target_id: targetId },
});

// If voteScore is null (no matching votes), return 0
const totalVoteScore = voteScore !== null ? voteScore : 0;

result(responseHandler(true, 200, 'Total vote score retrieved successfully', {votes : totalVoteScore}), totalVoteScore);
} catch (error) {
console.log(error);
result(responseHandler(false, 500, 'Failed to get total vote score', null), null);
}
};

exports.removeAllVotes = async (targetType, targetId, t) => {
await VotesModel
.destroy({ where: { target_type: targetType,target_id:targetId, } }, { transaction: t })
.then(() => ({ status: true, message: 'Votes Removed' }))
.catch((error) => {
throw new Error(`Votes Delete Operation Failed: ${error}`);
});
};


1 change: 1 addition & 0 deletions src/routers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ router.use('/posts', require('./posts.router'));
router.use('/tags', require('./tags.router'));
router.use('/posts/answers', require('./answers.router'));
router.use('/posts/comments', require('./comments.router'));
router.use('/votes', require('./votes.router'));

module.exports = router;
26 changes: 26 additions & 0 deletions src/routers/votes.router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const express = require('express');
const { auth } = require('../middleware');
const { votesController } = require('../controllers');

const router = express.Router();

/** @route GET /api/votes/:target_type/:target_id
* @desc fetch all votes to a particular posts or answer
*/

router.route('/all/:target_type/:target_id')
.get(votesController.getAllVotes);


/** @route GET ,POST, DELETE /api/votes/:target_type/:target_id/:user_id
* @desc fetch,delete,update/add vote of user's vote of post or an answer ,
* target_type="posts/answer" target_id=id of posts/answers
*/

router.route('/:target_type/:target_id/')
.get(auth,votesController.getUserVote)
.post(auth,votesController.addVote)
.delete(auth, votesController.deleteVote)


module.exports = router;
19 changes: 18 additions & 1 deletion src/services/answers.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,23 @@ const { AnswersRepository } = require('../repositories');

exports.create = (newAnswer, result) => AnswersRepository.create(newAnswer, result);

exports.remove = (id, result) => AnswersRepository.remove(id, result);
exports.remove = async (id, result) => {
try {
t = await db.transaction();
await VotesRepository.removeAllVotes("answers",id,t)
await AnswersRepository.remove(id, result);
result(
null,
responseHandler(true, 200, 'Post Removed', null),
);

await t.commit();
} catch (error) {
console.log(error);
result(responseHandler(false, 500, 'Something went wrong', null), null);
await t.rollback();
}

}

exports.retrieveAll = (postId, result) => AnswersRepository.retrieveAll(postId, result);
Loading