From 34ec4c9f1bbd13a7a633bdd02425d207986baea3 Mon Sep 17 00:00:00 2001 From: eug-vs Date: Thu, 25 Jun 2020 10:39:32 +0300 Subject: feat: count votes by aggregate in convertPoll hook --- hooks/convertPoll.ts | 39 ++++++++++++++++++++------------------- 1 file changed, 20 insertions(+), 19 deletions(-) (limited to 'hooks') diff --git a/hooks/convertPoll.ts b/hooks/convertPoll.ts index aacf3de..b4f8376 100644 --- a/hooks/convertPoll.ts +++ b/hooks/convertPoll.ts @@ -1,32 +1,33 @@ import { HookContext } from '@feathersjs/feathers'; +import { Types } from 'mongoose'; import bluebird from 'bluebird'; import _ from 'lodash'; -import { Poll, User } from 'which-types'; +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 => { - const { app, result } = context; + const { app, result, params: { user } } = context; const convert = async (poll: PollSchema): Promise => { - return app.service('users').get(poll.authorId) - .then((author: User | null): Poll | null => { - return author && _.merge( - _.omit(poll, ['authorId']), - { - author, - contents: { - left: { - votes: poll.contents.left.votes.length - }, - right: { - votes: poll.contents.right.votes.length - } - } - } - ); - }); + 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), + {} + )); + + const userChoice = await VoteModel.findOne({ pollId: poll._id, userId: user?._id }); + + return _.merge( + _.omit(poll, ['authorId']), + { author, contents, userChoice } + ); }; if (Array.isArray(result)) { -- cgit v1.2.3