Fixed user voting

pull/2/head
Trivernis 5 years ago
parent 57338355a7
commit 511a446c71

@ -111,7 +111,7 @@ export function resolver(req: any, res: any): any {
if (postId && type) {
if (req.session.userId) {
const post = await models.SqPost.findByPk(postId);
return await (post.post).vote(req.session.userId, type);
return await post.post.vote(req.session.userId, type);
} else {
res.status(status.UNAUTHORIZED);
return new NotLoggedInGqlError();

@ -74,10 +74,22 @@ export class Post {
* @param type
*/
public async vote(userId: number, type: dataaccess.VoteType): Promise<dataaccess.VoteType> {
const [vote, _] = await SqPostVotes
.findOrCreate({where: {userId}, defaults: {voteType: type, postId: this.post.id}});
type = type || dataaccess.VoteType.UPVOTE;
let vote = await SqPostVotes.findOne({where: {user_id: userId, post_id: this.id}});
if (!vote) {
await this.post.addVote(userId);
vote = await SqPostVotes.findOne({where: {user_id: userId, post_id: this.id}});
}
if (vote) {
if (vote.voteType === type) {
await vote.destroy();
return null;
} else {
vote.voteType = type;
await vote.save();
}
}
return vote.voteType;
}
}

Loading…
Cancel
Save