]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - core-utils/plugins/hooks.ts
Bumped to version v5.2.1
[github/Chocobozzz/PeerTube.git] / 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> (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
20 try {
21 if (hookType === HookType.FILTER) {
22 const p = handler(result, params)
23
24 const newResult = isPromise(p)
25 ? await p
26 : p
27
28 return newResult
29 }
30
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 }
39
40 if (hookType === HookType.ACTION) {
41 if (isCatchable(p)) p.catch((err: any) => onError(err))
42
43 return undefined
44 }
45 } catch (err) {
46 onError(err)
47 }
48
49 return result
50 }
51
52 export {
53 getHookType,
54 internalRunHook
55 }