]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/core-utils/plugins/hooks.ts
Merge branch 'release/5.0.0' into develop
[github/Chocobozzz/PeerTube.git] / shared / core-utils / plugins / hooks.ts
1 import { RegisteredExternalAuthConfig } from '@shared/models'
2 import { HookType } from '../../models/plugins/hook-type.enum'
3 import { isCatchable, isPromise } from '../common/promises'
4
5 function getHookType (hookName: string) {
6 if (hookName.startsWith('filter:')) return HookType.FILTER
7 if (hookName.startsWith('action:')) return HookType.ACTION
8
9 return HookType.STATIC
10 }
11
12 async function internalRunHook <T> (options: {
13 handler: Function
14 hookType: HookType
15 result: T
16 params: any
17 onError: (err: Error) => void
18 }) {
19 const { handler, hookType, result, params, onError } = options
20
21 try {
22 if (hookType === HookType.FILTER) {
23 const p = handler(result, params)
24
25 const newResult = isPromise(p)
26 ? await p
27 : p
28
29 return newResult
30 }
31
32 // Action/static hooks do not have result value
33 const p = handler(params)
34
35 if (hookType === HookType.STATIC) {
36 if (isPromise(p)) await p
37
38 return undefined
39 }
40
41 if (hookType === HookType.ACTION) {
42 if (isCatchable(p)) p.catch((err: any) => onError(err))
43
44 return undefined
45 }
46 } catch (err) {
47 onError(err)
48 }
49
50 return result
51 }
52
53 function getExternalAuthHref (apiUrl: string, auth: RegisteredExternalAuthConfig) {
54 return apiUrl + `/plugins/${auth.name}/${auth.version}/auth/${auth.authName}`
55 }
56
57 export {
58 getHookType,
59 internalRunHook,
60 getExternalAuthHref
61 }