diff options
author | Eugene Sokolov <eug-vs@keemail.me> | 2020-06-28 19:01:52 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-06-28 19:01:52 +0300 |
commit | 88e97a42096c1e4de7b9f1d8fefa0829bbc0d321 (patch) | |
tree | ae402f77d0d0d7b8d06dcefc614bbb9aad12ed59 /services/polls/polls.hooks.ts | |
parent | 8baf96be5ea7880cebe3aeda733b9196950be434 (diff) | |
parent | 29197dd3bc7e941707979b6c226e5f3b1a4cbbed (diff) | |
download | which-api-88e97a42096c1e4de7b9f1d8fefa0829bbc0d321.tar.gz |
Merge pull request #16 from which-ecosystem/feedback
Feedback endpoint & schema updates
Diffstat (limited to 'services/polls/polls.hooks.ts')
-rw-r--r-- | services/polls/polls.hooks.ts | 43 |
1 files changed, 42 insertions, 1 deletions
diff --git a/services/polls/polls.hooks.ts b/services/polls/polls.hooks.ts index 77fcc7a..9f2183f 100644 --- a/services/polls/polls.hooks.ts +++ b/services/polls/polls.hooks.ts @@ -1,6 +1,47 @@ -import convertPoll from '../../hooks/convertPoll'; +import { HookContext } from '@feathersjs/feathers'; +import { Types } from 'mongoose'; +import bluebird from 'bluebird'; import _ from 'lodash'; +import { Poll } from 'which-types'; + +import { PollSchema } from '../../models/polls/poll.schema'; +import VoteModel from '../../models/votes/vote.model'; import sortByDate from '../../hooks/sortByDate'; + +const convertPoll = 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 vote = await VoteModel.findOne( + { pollId: poll._id, authorId: user?._id } + ); + + return _.merge( + _.omit(poll, ['authorId']), + { author, contents, vote } + ); + }; + + 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; +}; + + export default { before: { find: sortByDate |