|
1 |
| -import convertPoll from '../../hooks/convertPoll'; |
| 1 | +import { HookContext } from '@feathersjs/feathers'; |
| 2 | +import { Types } from 'mongoose'; |
| 3 | +import bluebird from 'bluebird'; import _ from 'lodash'; |
| 4 | +import { Poll } from 'which-types'; |
| 5 | + |
| 6 | +import { PollSchema } from '../../models/polls/poll.schema'; |
| 7 | +import VoteModel from '../../models/votes/vote.model'; |
2 | 8 | import sortByDate from '../../hooks/sortByDate';
|
3 | 9 |
|
| 10 | + |
| 11 | +const convertPoll = async (context: HookContext): Promise<HookContext> => { |
| 12 | + const { app, result, params: { user } } = context; |
| 13 | + |
| 14 | + const convert = async (poll: PollSchema): Promise<Poll | null> => { |
| 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 | + { left: { votes: 0 }, right: { votes: 0 } } |
| 23 | + )); |
| 24 | + |
| 25 | + const vote = await VoteModel.findOne( |
| 26 | + { pollId: poll._id, authorId: user?._id } |
| 27 | + ); |
| 28 | + |
| 29 | + return _.merge( |
| 30 | + _.omit(poll, ['authorId']), |
| 31 | + { author, contents, vote } |
| 32 | + ); |
| 33 | + }; |
| 34 | + |
| 35 | + if (Array.isArray(result)) { |
| 36 | + const polls = await bluebird.map(result, (poll: PollSchema) => convert(poll)); |
| 37 | + context.result = _.compact(polls); |
| 38 | + } else { |
| 39 | + context.result = await convert(result); |
| 40 | + } |
| 41 | + return context; |
| 42 | +}; |
| 43 | + |
| 44 | + |
4 | 45 | export default {
|
5 | 46 | before: {
|
6 | 47 | find: sortByDate
|
|
0 commit comments