diff options
author | eug-vs <eug-vs@keemail.me> | 2020-06-23 22:50:59 +0300 |
---|---|---|
committer | eug-vs <eug-vs@keemail.me> | 2020-06-23 22:50:59 +0300 |
commit | dbfb0d30f0e5cd44ea188d72ceb05acac2ac40d7 (patch) | |
tree | 8372becdf6de9cb0bd98899ec8608eaa3143ff0d | |
parent | 5255b85532f2e2709b31e891a167c1a250a0aa7e (diff) | |
download | which-api-dbfb0d30f0e5cd44ea188d72ceb05acac2ac40d7.tar.gz |
feat: only allow voting once
-rw-r--r-- | models/polls/poll.model.ts | 13 | ||||
-rw-r--r-- | models/polls/poll.schema.ts | 2 | ||||
-rw-r--r-- | 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<PollSchema, Model<PollSchema>>('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<PollSchema | null> { 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; } |