Skip to content

Commit a58354a

Browse files
committed
feat: validate fields in votes
1 parent 681e51a commit a58354a

File tree

3 files changed

+12
-11
lines changed

3 files changed

+12
-11
lines changed

models/votes/vote.model.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { Model, model } from 'mongoose';
22
import { VoteSchema, voteSchema } from './vote.schema';
33

4+
voteSchema.index({ pollId: 1, userId: 1 }, { unique: true }); // Unique together
5+
46
export default model<VoteSchema, Model<VoteSchema>>('Vote', voteSchema);
57

models/votes/vote.schema.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,18 @@ export interface VoteSchema extends Document, Omit<Vote, '_id'> {
88
export const voteSchema = new Schema({
99
userId: {
1010
type: Types.ObjectId,
11-
ref: 'user'
11+
ref: 'user',
12+
required: true
1213
},
1314
pollId: {
1415
type: Types.ObjectId,
15-
ref: 'poll'
16+
ref: 'poll',
17+
required: true
1618
},
1719
which: {
1820
type: String,
19-
enum: ['left', 'right']
21+
enum: ['left', 'right'],
22+
required: true
2023
}
2124
}, { timestamps: true });
2225

populateDb.ts

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import app from './app';
88
mongoose.connect('mongodb://localhost:27017/which', { useNewUrlParser: true });
99

1010
const POLLS_AMOUNT = 20;
11-
const VOTES_AMOUNT = 160;
1211

1312
const imageUrls: string[] = [
1413
// eslint-disable max-len
@@ -59,10 +58,9 @@ const createUser = (username: string): Promise<User> => {
5958

6059
const createVote = (userId: string, pollId: string): Promise<Vote> => {
6160
return app.service('votes').create({
62-
userId,
6361
pollId,
6462
which: _.sample(choices)
65-
});
63+
}, { user: { _id: userId } });
6664
}
6765

6866

@@ -72,13 +70,11 @@ const populate = async () => {
7270
const polls = await bluebird.mapSeries(new Array(POLLS_AMOUNT), async () => {
7371
const user = _.sample(users);
7472
return createPoll(user?._id || '');
75-
7673
});
7774

78-
const votes = await bluebird.mapSeries(new Array(VOTES_AMOUNT), async () => {
79-
const user = _.sample(users);
80-
const poll = _.sample(polls);
81-
return createVote(user?._id || '', poll?._id || '');
75+
const votes = await bluebird.map(users, user => {
76+
const pollsToVote = _.sampleSize(polls, _.random(0, POLLS_AMOUNT));
77+
return bluebird.map(pollsToVote, poll => createVote(user?._id || '', poll?._id || ''));
8278
});
8379
};
8480

0 commit comments

Comments
 (0)