File tree Expand file tree Collapse file tree 3 files changed +16
-6
lines changed Expand file tree Collapse file tree 3 files changed +16
-6
lines changed Original file line number Diff line number Diff line change 1
1
import { Model , model } from 'mongoose' ;
2
2
import { PollSchema , pollSchema } from './poll.schema' ;
3
3
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
+
4
17
export default model < PollSchema , Model < PollSchema > > ( 'Poll' , pollSchema ) ;
5
18
Original file line number Diff line number Diff line change @@ -11,7 +11,7 @@ export interface PollSchema extends Document {
11
11
right : ImageDataSchema ;
12
12
} ;
13
13
authorId : string ;
14
- vote : ( userId : string , which : 'left' | 'right' ) => void ;
14
+ vote : ( userId : string , which : 'left' | 'right' ) => PollSchema ;
15
15
}
16
16
17
17
export const imageDataSchema = {
Original file line number Diff line number Diff line change @@ -5,11 +5,8 @@ export default class Votes {
5
5
async create ( data : any , params : any ) : Promise < PollSchema | null > {
6
6
const poll = await PollModel . findById ( params . route . id ) ;
7
7
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 ( ) ;
13
10
}
14
11
return null ;
15
12
}
You can’t perform that action at this time.
0 commit comments