Skip to content

Commit dbfb0d3

Browse files
committed
feat: only allow voting once
1 parent 5255b85 commit dbfb0d3

File tree

3 files changed

+16
-6
lines changed

3 files changed

+16
-6
lines changed

models/polls/poll.model.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,18 @@
11
import { Model, model } from 'mongoose';
22
import { PollSchema, pollSchema } from './poll.schema';
33

4+
pollSchema.methods.vote = function(userId: string, which: 'left' | 'right'): PollSchema {
5+
const participants = ['left', 'right'].reduce((acc, option) => {
6+
const { votes } = this.contents[option];
7+
return acc.concat(votes);
8+
}, []);
9+
10+
if (!participants.indexOf(userId) === -1) {
11+
this.contents[which].votes.push(userId);
12+
}
13+
14+
return this.save();
15+
}
16+
417
export default model<PollSchema, Model<PollSchema>>('Poll', pollSchema);
518

models/polls/poll.schema.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ export interface PollSchema extends Document {
1111
right: ImageDataSchema;
1212
};
1313
authorId: string;
14-
vote: (userId: string, which: 'left' | 'right') => void;
14+
vote: (userId: string, which: 'left' | 'right') => PollSchema;
1515
}
1616

1717
export const imageDataSchema = {

services/votes/votes.class.ts

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,8 @@ export default class Votes {
55
async create(data: any, params: any): Promise<PollSchema | null> {
66
const poll = await PollModel.findById(params.route.id);
77
if (poll) {
8-
const which: 'left' | 'right' = data.which;
9-
const { user } = params;
10-
poll.contents[which].votes.push(user._id);
11-
poll.save();
12-
return poll.toObject();
8+
const updatedPoll = await poll.vote(params.user._id, data.which);
9+
return updatedPoll.toObject();
1310
}
1411
return null;
1512
}

0 commit comments

Comments
 (0)