]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - shared/core-utils/plugins/hooks.ts
Add client hooks
[github/Chocobozzz/PeerTube.git] / shared / core-utils / plugins / hooks.ts
CommitLineData
b4055e1c
C
1import { HookType } from '../../models/plugins/hook-type.enum'
2import { isCatchable, isPromise } from '../miscs/miscs'
3
4function 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
587568e1 11async function internalRunHook <T> (handler: Function, hookType: HookType, result: T, params: any, onError: (err: Error) => void) {
b4055e1c 12 try {
89cd1275
C
13 if (hookType === HookType.FILTER) {
14 const p = handler(result, params)
15
16 if (isPromise(p)) result = await p
17 else result = p
18
19 return result
20 }
b4055e1c 21
89cd1275
C
22 // Action/static hooks do not have result value
23 const p = handler(params)
24
25 if (hookType === HookType.STATIC) {
26 if (isPromise(p)) await p
27
28 return undefined
29 }
b4055e1c 30
89cd1275 31 if (hookType === HookType.ACTION) {
93cae479 32 if (isCatchable(p)) p.catch((err: any) => onError(err))
b4055e1c 33
89cd1275 34 return undefined
b4055e1c
C
35 }
36 } catch (err) {
37 onError(err)
38 }
39
40 return result
41}
42
43export {
44 getHookType,
45 internalRunHook
46}