|
1 | 1 | import { HookContext } from '@feathersjs/feathers';
|
| 2 | +import { Types } from 'mongoose'; |
2 | 3 | import bluebird from 'bluebird';
|
3 | 4 | import _ from 'lodash';
|
4 |
| -import { Poll, User } from 'which-types'; |
| 5 | +import { Poll, User, Vote } from 'which-types'; |
5 | 6 |
|
6 | 7 | import { PollSchema } from '../models/polls/poll.schema';
|
| 8 | +import VoteModel from '../models/votes/vote.model'; |
7 | 9 |
|
8 | 10 |
|
9 | 11 | export default async (context: HookContext): Promise<HookContext> => {
|
10 |
| - const { app, result } = context; |
| 12 | + const { app, result, params: { user } } = context; |
11 | 13 |
|
12 | 14 | 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 |
| - } |
26 |
| - } |
27 |
| - } |
28 |
| - ); |
29 |
| - }); |
| 15 | + const author = await app.service('users').get(poll.authorId); |
| 16 | + |
| 17 | + const contents = await VoteModel.aggregate([ |
| 18 | + { $match: { pollId: Types.ObjectId(poll._id) } }, |
| 19 | + { $group: { _id: '$which', total: { $sum: 1 } } } |
| 20 | + ]).then(groups => groups.reduce( |
| 21 | + (acc, group) => _.set(acc, group._id + '.votes', group.total), |
| 22 | + {} |
| 23 | + )); |
| 24 | + |
| 25 | + const userChoice = await VoteModel.findOne({ pollId: poll._id, userId: user?._id }); |
| 26 | + |
| 27 | + return _.merge( |
| 28 | + _.omit(poll, ['authorId']), |
| 29 | + { author, contents, userChoice } |
| 30 | + ); |
30 | 31 | };
|
31 | 32 |
|
32 | 33 | if (Array.isArray(result)) {
|
|
0 commit comments