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 +- 2 files changed, 14 insertions(+), 1 deletion(-) (limited to 'models') 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 = { -- cgit v1.2.3