diff options
author | Eugene Sokolov <eug-vs@keemail.me> | 2020-06-25 14:39:21 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-06-25 14:39:21 +0300 |
commit | 0afe8f1530affad1e58a65385b2a4bf888ab86cb (patch) | |
tree | 3bd5599bc5c3ce23777c5b369eaadd744f3c5c1f /hooks/convertPoll.ts | |
parent | e488591b9548264d0305a5f34786138bd6c6622b (diff) | |
parent | 64f5f8c3f9660f649dfdaad07d84aa8c26b9661e (diff) | |
download | which-api-0afe8f1530affad1e58a65385b2a4bf888ab86cb.tar.gz |
Merge pull request #8 from which-ecosystem/votes
Votes
Diffstat (limited to 'hooks/convertPoll.ts')
-rw-r--r-- | hooks/convertPoll.ts | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/hooks/convertPoll.ts b/hooks/convertPoll.ts new file mode 100644 index 0000000..1c32851 --- /dev/null +++ b/hooks/convertPoll.ts @@ -0,0 +1,43 @@ +import { HookContext } from '@feathersjs/feathers'; +import { Types } from 'mongoose'; +import bluebird from 'bluebird'; +import _ from 'lodash'; +import { Poll, User, Vote } from 'which-types'; + +import { PollSchema } from '../models/polls/poll.schema'; +import VoteModel from '../models/votes/vote.model'; + + +export default async (context: HookContext): Promise<HookContext> => { + const { app, result, params: { user } } = context; + + const convert = async (poll: PollSchema): Promise<Poll | null> => { + const author = await app.service('users').get(poll.authorId); + + const contents = await VoteModel.aggregate([ + { $match: { pollId: Types.ObjectId(poll._id) } }, + { $group: { _id: '$which', total: { $sum: 1 } } } + ]).then(groups => groups.reduce( + (acc, group) => _.set(acc, group._id + '.votes', group.total), + { left: { votes: 0 }, right: { votes: 0 } } + )); + + const userChoice = await VoteModel.findOne( + { pollId: poll._id, userId: user?._id } + ).then(vote => vote?.which); + + return _.merge( + _.omit(poll, ['authorId']), + { author, contents, userChoice } + ); + }; + + if (Array.isArray(result)) { + const polls = await bluebird.map(result, (poll: PollSchema) => convert(poll)); + context.result = _.compact(polls); + } else { + context.result = await convert(result); + } + return context; +}; + |