Skip to content

Commit c3438eb

Browse files
committed
refactor: move convertPoll to polls hooks
1 parent 02b0da0 commit c3438eb

File tree

3 files changed

+44
-46
lines changed

3 files changed

+44
-46
lines changed

hooks/convertPoll.ts

Lines changed: 0 additions & 43 deletions
This file was deleted.

services/feed/feed.hooks.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ const raiseNewVerifedPolls = async (context: HookContext): Promise<HookContext>
77
// Raise unseen verified polls to the very top
88
context.result = _.sortBy(
99
context.result,
10-
poll => !(poll.author.verified && !poll.userChoice)
10+
poll => !(poll.author.verified && !poll.vote)
1111
);
1212
return context;
1313
};
@@ -16,7 +16,7 @@ const lowerOldPolls = async (context: HookContext): Promise<HookContext> => {
1616
// Move all seen polls down
1717
context.result = _.sortBy(
1818
context.result,
19-
poll => !!poll.userChoice
19+
poll => !!poll.vote
2020
);
2121
return context;
2222
};

services/polls/polls.hooks.ts

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,47 @@
1-
import convertPoll from '../../hooks/convertPoll';
1+
import { HookContext } from '@feathersjs/feathers';
2+
import { Types } from 'mongoose';
3+
import bluebird from 'bluebird'; import _ from 'lodash';
4+
import { Poll } from 'which-types';
5+
6+
import { PollSchema } from '../../models/polls/poll.schema';
7+
import VoteModel from '../../models/votes/vote.model';
28
import sortByDate from '../../hooks/sortByDate';
39

10+
11+
const convertPoll = async (context: HookContext): Promise<HookContext> => {
12+
const { app, result, params: { user } } = context;
13+
14+
const convert = async (poll: PollSchema): Promise<Poll | null> => {
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+
{ left: { votes: 0 }, right: { votes: 0 } }
23+
));
24+
25+
const vote = await VoteModel.findOne(
26+
{ pollId: poll._id, authorId: user?._id }
27+
);
28+
29+
return _.merge(
30+
_.omit(poll, ['authorId']),
31+
{ author, contents, vote }
32+
);
33+
};
34+
35+
if (Array.isArray(result)) {
36+
const polls = await bluebird.map(result, (poll: PollSchema) => convert(poll));
37+
context.result = _.compact(polls);
38+
} else {
39+
context.result = await convert(result);
40+
}
41+
return context;
42+
};
43+
44+
445
export default {
546
before: {
647
find: sortByDate

0 commit comments

Comments
 (0)