diff options
author | eug-vs <eug-vs@keemail.me> | 2020-06-28 18:33:58 +0300 |
---|---|---|
committer | eug-vs <eug-vs@keemail.me> | 2020-06-28 18:49:24 +0300 |
commit | c3438eb4a7187773e2736dea765bb8281f7edf0e (patch) | |
tree | 4397f49f436d8d1a79e3e09eaa291d6ae6a7cc27 /hooks | |
parent | 02b0da08155c6615a48b8d7f49648c19c1600020 (diff) | |
download | which-api-c3438eb4a7187773e2736dea765bb8281f7edf0e.tar.gz |
refactor: move convertPoll to polls hooks
Diffstat (limited to 'hooks')
-rw-r--r-- | hooks/convertPoll.ts | 43 |
1 files changed, 0 insertions, 43 deletions
diff --git a/hooks/convertPoll.ts b/hooks/convertPoll.ts deleted file mode 100644 index 5e6f9f4..0000000 --- a/hooks/convertPoll.ts +++ /dev/null @@ -1,43 +0,0 @@ -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'; - - -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; -}; - |