Skip to content

Commit fb88914

Browse files
committed
refactor: move hooks to global folder
1 parent c9fc9c1 commit fb88914

File tree

2 files changed

+38
-34
lines changed

2 files changed

+38
-34
lines changed

hooks/expandAuthor.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { HookContext } from '@feathersjs/feathers';
2+
import bluebird from 'bluebird';
3+
import _ from 'lodash';
4+
5+
import { Poll, PollSchema } from '../models/polls/poll.schema';
6+
import { User } from '../models/users/user.schema';
7+
import UserModel from '../models/users/user.model';
8+
9+
const expandAuthor = async (poll: PollSchema): Promise<Poll | null> => {
10+
return UserModel.findById(poll.authorId)
11+
.lean<User>()
12+
.exec()
13+
.then((author: User | null): Poll | null => {
14+
return author && _.merge(_.omit(poll, 'authorId'), { author });
15+
})
16+
.catch(err => {
17+
console.error(err);
18+
return err;
19+
});
20+
};
21+
22+
export const expandAuthorHook = async (context: HookContext): Promise<HookContext> => {
23+
context.result = await expandAuthor(context.result);
24+
return context;
25+
};
26+
27+
export const expandAuthorManyHook = async (context: HookContext): Promise<HookContext> => {
28+
const polls = await bluebird.map(context.result, (poll: any) => expandAuthor(poll));
29+
context.result = _.compact(polls);
30+
return context;
31+
};
32+

services/polls/polls.hooks.ts

Lines changed: 6 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,12 @@
1-
import { HookContext } from '@feathersjs/feathers';
2-
import bluebird from 'bluebird';
3-
import _ from 'lodash';
4-
5-
import { Poll, PollSchema } from '../../models/polls/poll.schema';
6-
import { User } from '../../models/users/user.schema';
7-
import UserModel from '../../models/users/user.model';
8-
9-
10-
const expandAuthor = async (poll: PollSchema): Promise<Poll | null> => {
11-
return UserModel.findById(poll.authorId)
12-
.lean<User>()
13-
.exec()
14-
.then((author: User | null): Poll | null => {
15-
return author && _.merge(_.omit(poll, 'authorId'), { author });
16-
})
17-
.catch(err => {
18-
console.error(err);
19-
return err;
20-
});
21-
};
22-
23-
const expandAuthorHook = async (context: HookContext): Promise<HookContext> => {
24-
context.result = await expandAuthor(context.result);
25-
return context;
26-
};
27-
28-
const expandAuthorManyHook = async (context: HookContext): Promise<HookContext> => {
29-
const polls = await bluebird.map(context.result, (poll: any) => expandAuthor(poll));
30-
context.result = _.compact(polls);
31-
return context;
32-
};
33-
1+
import {
2+
expandAuthorHook,
3+
expandAuthorManyHook
4+
} from '../../hooks/expandAuthor';
345

356
export default {
367
after: {
378
get: [expandAuthorHook],
389
find: [expandAuthorManyHook]
3910
}
40-
}
11+
};
12+

0 commit comments

Comments
 (0)