Skip to content

Commit 34ec4c9

Browse files
committed
feat: count votes by aggregate in convertPoll hook
1 parent edcd782 commit 34ec4c9

File tree

1 file changed

+20
-19
lines changed

1 file changed

+20
-19
lines changed

hooks/convertPoll.ts

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,33 @@
11
import { HookContext } from '@feathersjs/feathers';
2+
import { Types } from 'mongoose';
23
import bluebird from 'bluebird';
34
import _ from 'lodash';
4-
import { Poll, User } from 'which-types';
5+
import { Poll, User, Vote } from 'which-types';
56

67
import { PollSchema } from '../models/polls/poll.schema';
8+
import VoteModel from '../models/votes/vote.model';
79

810

911
export default async (context: HookContext): Promise<HookContext> => {
10-
const { app, result } = context;
12+
const { app, result, params: { user } } = context;
1113

1214
const convert = async (poll: PollSchema): Promise<Poll | null> => {
13-
return app.service('users').get(poll.authorId)
14-
.then((author: User | null): Poll | null => {
15-
return author && _.merge(
16-
_.omit(poll, ['authorId']),
17-
{
18-
author,
19-
contents: {
20-
left: {
21-
votes: poll.contents.left.votes.length
22-
},
23-
right: {
24-
votes: poll.contents.right.votes.length
25-
}
26-
}
27-
}
28-
);
29-
});
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+
{}
23+
));
24+
25+
const userChoice = await VoteModel.findOne({ pollId: poll._id, userId: user?._id });
26+
27+
return _.merge(
28+
_.omit(poll, ['authorId']),
29+
{ author, contents, userChoice }
30+
);
3031
};
3132

3233
if (Array.isArray(result)) {

0 commit comments

Comments
 (0)