From 511a446c719b1abfdc0794e5f1aecf55dcd6d935 Mon Sep 17 00:00:00 2001 From: Trivernis Date: Sun, 13 Oct 2019 00:20:46 +0200 Subject: [PATCH] Fixed user voting --- src/graphql/resolvers.ts | 2 +- src/lib/dataaccess/Post.ts | 20 ++++++++++++++++---- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/graphql/resolvers.ts b/src/graphql/resolvers.ts index 23745e3..fe4e76a 100644 --- a/src/graphql/resolvers.ts +++ b/src/graphql/resolvers.ts @@ -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(); diff --git a/src/lib/dataaccess/Post.ts b/src/lib/dataaccess/Post.ts index 1105499..db6690c 100644 --- a/src/lib/dataaccess/Post.ts +++ b/src/lib/dataaccess/Post.ts @@ -74,10 +74,22 @@ export class Post { * @param type */ public async vote(userId: number, type: dataaccess.VoteType): Promise { - const [vote, _] = await SqPostVotes - .findOrCreate({where: {userId}, defaults: {voteType: type, postId: this.post.id}}); - vote.voteType = type; - await vote.save(); + 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; } }