@@ -4,42 +4,37 @@ import _ from 'lodash';
4
4
import { Poll , User } from 'which-types' ;
5
5
6
6
import { PollSchema } from '../models/polls/poll.schema' ;
7
- import UserModel from '../models/users/user.model' ;
8
7
9
- const convertPoll = async ( poll : PollSchema ) : Promise < Poll | null > => {
10
- return UserModel . findById ( poll . authorId )
11
- . lean < User > ( )
12
- . exec ( )
13
- . then ( ( author : User | null ) : Poll | null => {
14
- return author && _ . merge (
15
- _ . omit ( poll , [ 'authorId' ] ) ,
16
- {
17
- author,
18
- contents : {
19
- left : {
20
- votes : poll . contents . left . votes . length
21
- } ,
22
- right : {
23
- votes : poll . contents . right . votes . length
8
+
9
+ export default async ( context : HookContext ) : Promise < HookContext > => {
10
+ const { app, result } = context ;
11
+
12
+ const convert = async ( poll : PollSchema ) : Promise < Poll | null > => {
13
+ return app . service ( 'users' ) . get ( poll . authorId )
14
+ . then ( ( author : User | null ) : Poll | null => {
15
+ return author && _ . merge (
16
+ _ . omit ( poll , [ 'authorId' ] ) ,
17
+ {
18
+ author,
19
+ contents : {
20
+ left : {
21
+ votes : poll . contents . left . votes . length
22
+ } ,
23
+ right : {
24
+ votes : poll . contents . right . votes . length
25
+ }
24
26
}
25
27
}
26
- }
27
- ) ;
28
- } )
29
- . catch ( err => {
30
- console . error ( err ) ;
31
- return err ;
32
- } ) ;
33
- } ;
34
-
35
- export const convertPollHook = async ( context : HookContext ) : Promise < HookContext > => {
36
- context . result = await convertPoll ( context . result ) ;
37
- return context ;
38
- } ;
28
+ ) ;
29
+ } ) ;
30
+ } ;
39
31
40
- export const convertPollManyHook = async ( context : HookContext ) : Promise < HookContext > => {
41
- const polls = await bluebird . map ( context . result , ( poll : PollSchema ) => convertPoll ( poll ) ) ;
42
- context . result = _ . compact ( polls ) ;
32
+ if ( Array . isArray ( result ) ) {
33
+ const polls = await bluebird . map ( result , ( poll : PollSchema ) => convert ( poll ) ) ;
34
+ context . result = _ . compact ( polls ) ;
35
+ } else {
36
+ context . result = await convert ( result ) ;
37
+ }
43
38
return context ;
44
39
} ;
45
40
0 commit comments