Skip to content

Commit 709416b

Browse files
committed
feat: add expandAuthor hook to polls
1 parent fd03f26 commit 709416b

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

services/polls/polls.hooks.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { HookContext } from '@feathersjs/feathers';
2+
import bluebird from 'bluebird';
3+
import _ from 'lodash';
4+
5+
import { PollSchema } from '../../models/polls/poll.schema';
6+
import { UserSchema } from '../../models/users/user.schema';
7+
import UserModel from '../../models/users/user.model';
8+
9+
10+
interface Poll extends Omit<PollSchema, 'authorId'> {
11+
author: UserSchema;
12+
}
13+
14+
const expandAuthor = async (poll: PollSchema): Promise<Poll | null> => {
15+
return UserModel.findById(poll.authorId).then((author: UserSchema | null): Poll | null => {
16+
if (author) return _.merge(_.omit(poll, 'authorId'), { author });
17+
return null;
18+
});
19+
};
20+
21+
const expandAuthorHook = async (context: HookContext): Promise<HookContext> => {
22+
context.result = await expandAuthor(context.result);
23+
return context;
24+
};
25+
26+
const expandAuthorManyHook = async (context: HookContext): Promise<HookContext> => {
27+
context.result = await bluebird.map(context.result, (poll: any) => expandAuthor(poll));
28+
console.log(context.result);
29+
return context;
30+
};
31+
32+
33+
export default {
34+
after: {
35+
get: [expandAuthorHook],
36+
find: [expandAuthorManyHook]
37+
}
38+
}

services/polls/polls.service.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
import { Application } from '@feathersjs/express';
22
import Model from '../../models/polls/poll.model';
33
import service from 'feathers-mongoose';
4+
import hooks from './polls.hooks'
45

56
const PollService = service({ Model });
67

78
export default (app: Application): void => {
89
app.use('/polls', PollService);
10+
app.service('polls').hooks(hooks);
911
};
1012

0 commit comments

Comments
 (0)