Skip to content

Commit

Permalink
Merge pull request #70 from chingu-voyage3/feature/upvote-answer
Browse files Browse the repository at this point in the history
Upvote answer (closes #54)
  • Loading branch information
J Player authored Jan 15, 2018
2 parents 50d62e4 + c7b660f commit a60798a
Show file tree
Hide file tree
Showing 6 changed files with 187 additions and 2 deletions.
45 changes: 45 additions & 0 deletions server/controller/answers.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,51 @@ exports.flag = async (ctx) => {
? { $pull: { flagged_by: user_id } }
: { $addToSet: { flagged_by: user_id } };

await Answer.findOneAndUpdate(
{ _id: ctx.params.id },
updates,
{ new: true }
).then((answer) => {
ctx.body = answer;
});
})
.catch((error) => {
ctx.body = { error };
});

return ctx.body;
};

exports.vote = async (ctx) => {
const { user_id } = ctx.request.body;

if (!user_id) {
ctx.body = { error: 'user_id is required' };
return ctx.body;
}

await Answer.findOne(
{ _id: ctx.params.id },
'-_id voted_by',
)
.then(async (res) => {
if (!res) {
ctx.body = { error: 'Answer ID not found' };
return ctx.body;
}

const userVoted = res.voted_by.includes(user_id);

const updates = userVoted
? {
$pull: { voted_by: user_id },
$inc: { votes: -1 },
}
: {
$addToSet: { voted_by: user_id },
$inc: { votes: 1 },
};

await Answer.findOneAndUpdate(
{ _id: ctx.params.id },
updates,
Expand Down
1 change: 0 additions & 1 deletion server/controller/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ exports.getId = async (ctx) => {
});
};


exports.markSpam = async (ctx) => {
const user = ctx.state.user.id;
if (!user) {
Expand Down
1 change: 1 addition & 0 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ router
.get('/api/answers/:id', AnswerController.findAnswersById)
.post('/api/answer', AnswerController.validateAnswer, AnswerController.addAnswer)
.post('/api/answer/:id/flag', AnswerController.flag)
.post('/api/answer/:id/vote', AnswerController.vote)
.post('/api/questions/:id/spam', QuestionController.markSpam);

app
Expand Down
3 changes: 2 additions & 1 deletion server/models/answer.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const answerSchema = mongoose.Schema(
question_id: { type: mongoose.Schema.Types.ObjectId, required: true },
body: { type: String, required: true },
votes: { type: Number, default: 0 },
voted_by: Array,
flagged_by: Array,
author: {
_id: String,
Expand All @@ -14,7 +15,7 @@ const answerSchema = mongoose.Schema(
},
{
timestamps: { createdAt: 'submitted_at', updatedAt: 'updated_at' },
},
}
);

const answerModel = mongoose.model('Answer', answerSchema);
Expand Down
Loading

0 comments on commit a60798a

Please sign in to comment.