]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/core-utils/plugins/hooks.ts
Move typescript utils in its own directory
[github/Chocobozzz/PeerTube.git] / shared / core-utils / plugins / hooks.ts
1 import { HookType } from '../../models/plugins/hook-type.enum'
2 import { isCatchable, isPromise } from '../common/promises'
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
11 async function internalRunHook <T> (handler: Function, hookType: HookType, result: T, params: any, onError: (err: Error) => void) {
12 try {
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 }
21
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 }
30
31 if (hookType === HookType.ACTION) {
32 if (isCatchable(p)) p.catch((err: any) => onError(err))
33
34 return undefined
35 }
36 } catch (err) {
37 onError(err)
38 }
39
40 return result
41 }
42
43 export {
44 getHookType,
45 internalRunHook
46 }