|
| 1 | +import { HookContext } from '@feathersjs/feathers'; |
| 2 | +import { Types } from 'mongoose'; |
| 3 | +import bluebird from 'bluebird'; |
| 4 | +import _ from 'lodash'; |
| 5 | +import { Poll, User, Vote } from 'which-types'; |
| 6 | + |
| 7 | +import { PollSchema } from '../models/polls/poll.schema'; |
| 8 | +import VoteModel from '../models/votes/vote.model'; |
| 9 | + |
| 10 | + |
| 11 | +export default 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 userChoice = await VoteModel.findOne( |
| 26 | + { pollId: poll._id, userId: user?._id } |
| 27 | + ).then(vote => vote?.which); |
| 28 | + |
| 29 | + return _.merge( |
| 30 | + _.omit(poll, ['authorId']), |
| 31 | + { author, contents, userChoice } |
| 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 | + |
0 commit comments