]>
Commit | Line | Data |
---|---|---|
b4055e1c | 1 | import { HookType } from '../../models/plugins/hook-type.enum' |
15a7eafb | 2 | import { isCatchable, isPromise } from '../common/promises' |
b4055e1c C |
3 | |
4 | function getHookType (hookName: string) { | |
5 | if (hookName.startsWith('filter:')) return HookType.FILTER | |
6 | if (hookName.startsWith('action:')) return HookType.ACTION | |
7 | ||
8 | return HookType.STATIC | |
9 | } | |
10 | ||
22df69fd C |
11 | async function internalRunHook <T> (options: { |
12 | handler: Function | |
13 | hookType: HookType | |
14 | result: T | |
15 | params: any | |
16 | onError: (err: Error) => void | |
17 | }) { | |
18 | const { handler, hookType, result, params, onError } = options | |
19 | ||
b4055e1c | 20 | try { |
89cd1275 C |
21 | if (hookType === HookType.FILTER) { |
22 | const p = handler(result, params) | |
23 | ||
22df69fd C |
24 | const newResult = isPromise(p) |
25 | ? await p | |
26 | : p | |
89cd1275 | 27 | |
22df69fd | 28 | return newResult |
89cd1275 | 29 | } |
b4055e1c | 30 | |
89cd1275 C |
31 | // Action/static hooks do not have result value |
32 | const p = handler(params) | |
33 | ||
34 | if (hookType === HookType.STATIC) { | |
35 | if (isPromise(p)) await p | |
36 | ||
37 | return undefined | |
38 | } | |
b4055e1c | 39 | |
89cd1275 | 40 | if (hookType === HookType.ACTION) { |
93cae479 | 41 | if (isCatchable(p)) p.catch((err: any) => onError(err)) |
b4055e1c | 42 | |
89cd1275 | 43 | return undefined |
b4055e1c C |
44 | } |
45 | } catch (err) { | |
46 | onError(err) | |
47 | } | |
48 | ||
49 | return result | |
50 | } | |
51 | ||
52 | export { | |
53 | getHookType, | |
54 | internalRunHook | |
55 | } |