From dbfb0d30f0e5cd44ea188d72ceb05acac2ac40d7 Mon Sep 17 00:00:00 2001 From: eug-vs Date: Tue, 23 Jun 2020 22:50:59 +0300 Subject: feat: only allow voting once --- models/polls/poll.model.ts | 13 +++++++++++++ models/polls/poll.schema.ts | 2 +- services/votes/votes.class.ts | 7 ++----- 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/models/polls/poll.model.ts b/models/polls/poll.model.ts index 7f6be9a..ecd8ad8 100644 --- a/models/polls/poll.model.ts +++ b/models/polls/poll.model.ts @@ -1,5 +1,18 @@ import { Model, model } from 'mongoose'; import { PollSchema, pollSchema } from './poll.schema'; +pollSchema.methods.vote = function(userId: string, which: 'left' | 'right'): PollSchema { + const participants = ['left', 'right'].reduce((acc, option) => { + const { votes } = this.contents[option]; + return acc.concat(votes); + }, []); + + if (!participants.indexOf(userId) === -1) { + this.contents[which].votes.push(userId); + } + + return this.save(); +} + export default model>('Poll', pollSchema); diff --git a/models/polls/poll.schema.ts b/models/polls/poll.schema.ts index 0caa6b2..380c069 100644 --- a/models/polls/poll.schema.ts +++ b/models/polls/poll.schema.ts @@ -11,7 +11,7 @@ export interface PollSchema extends Document { right: ImageDataSchema; }; authorId: string; - vote: (userId: string, which: 'left' | 'right') => void; + vote: (userId: string, which: 'left' | 'right') => PollSchema; } export const imageDataSchema = { diff --git a/services/votes/votes.class.ts b/services/votes/votes.class.ts index 6b9181b..3220ee7 100644 --- a/services/votes/votes.class.ts +++ b/services/votes/votes.class.ts @@ -5,11 +5,8 @@ export default class Votes { async create(data: any, params: any): Promise { const poll = await PollModel.findById(params.route.id); if (poll) { - const which: 'left' | 'right' = data.which; - const { user } = params; - poll.contents[which].votes.push(user._id); - poll.save(); - return poll.toObject(); + const updatedPoll = await poll.vote(params.user._id, data.which); + return updatedPoll.toObject(); } return null; } -- cgit v1.2.3