From 7c2d12b4f809563cc08e86229359251674b745ce Mon Sep 17 00:00:00 2001 From: eug-vs Date: Sat, 27 Jun 2020 01:17:42 +0300 Subject: refactor: improve Feed service --- services/feed/feed.class.ts | 12 +----------- services/feed/feed.hooks.ts | 28 ++++++++++++++++++++++++++++ services/feed/feed.service.ts | 3 +++ 3 files changed, 32 insertions(+), 11 deletions(-) create mode 100644 services/feed/feed.hooks.ts diff --git a/services/feed/feed.class.ts b/services/feed/feed.class.ts index 8c7cd0b..3a2ffe4 100644 --- a/services/feed/feed.class.ts +++ b/services/feed/feed.class.ts @@ -1,23 +1,13 @@ -import _ from 'lodash'; import { Application } from '@feathersjs/express'; import { Params } from '@feathersjs/feathers'; import { Poll } from 'which-types'; -import { PollSchema } from '../../models/polls/poll.schema'; -import PollModel from '../../models/polls/poll.model'; - export default class Feed { app!: Application; async find(params: Params): Promise { - return this.app.service('polls') - .find(params) - .then( // Move new verified polls on top - (polls: Poll[]) => _.sortBy(polls, poll => poll.author.verified && !poll.userChoice) - ).then( // But all seen posts go down - (polls: Poll[]) => _.sortBy(polls, poll => !!poll.userChoice) - ); + return this.app.service('polls').find(params); } setup (app: Application) { diff --git a/services/feed/feed.hooks.ts b/services/feed/feed.hooks.ts new file mode 100644 index 0000000..0e201db --- /dev/null +++ b/services/feed/feed.hooks.ts @@ -0,0 +1,28 @@ +import _ from 'lodash'; +import { HookContext } from '@feathersjs/feathers'; + + +const raiseNewVerifedPolls = async (context: HookContext): Promise => { + // Raise unseen verified polls to the very top + context.result = _.sortBy( + context.result, + poll => !(poll.author.verified && !poll.userChoice) + ); + return context; +}; + +const lowerOldPolls = async (context: HookContext): Promise => { + // Move all seen polls down + context.result = _.sortBy( + context.result, + poll => !!poll.userChoice + ); + return context; +}; + +export default { + after: { + find: [raiseNewVerifedPolls, lowerOldPolls] + } +}; + diff --git a/services/feed/feed.service.ts b/services/feed/feed.service.ts index f641425..d326656 100644 --- a/services/feed/feed.service.ts +++ b/services/feed/feed.service.ts @@ -1,7 +1,10 @@ import { Application } from '@feathersjs/express'; import Feed from './feed.class'; +import hooks from './feed.hooks'; + export default (app: Application): void => { app.use('/feed', new Feed()); + app.service('feed').hooks(hooks); }; -- cgit v1.2.3