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 (postId && type) {
if (req.session.userId) { if (req.session.userId) {
const post = await models.SqPost.findByPk(postId); 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 { } else {
res.status(status.UNAUTHORIZED); res.status(status.UNAUTHORIZED);
return new NotLoggedInGqlError(); return new NotLoggedInGqlError();

@ -74,10 +74,22 @@ export class Post {
* @param type * @param type
*/ */
public async vote(userId: number, type: dataaccess.VoteType): Promise<dataaccess.VoteType> { public async vote(userId: number, type: dataaccess.VoteType): Promise<dataaccess.VoteType> {
const [vote, _] = await SqPostVotes type = type || dataaccess.VoteType.UPVOTE;
.findOrCreate({where: {userId}, defaults: {voteType: type, postId: this.post.id}}); 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; vote.voteType = type;
await vote.save(); await vote.save();
}
}
return vote.voteType; return vote.voteType;
} }
} }

Loading…
Cancel
Save