aboutsummaryrefslogtreecommitdiffhomepage
path: root/shared/core-utils/plugins/hooks.ts
blob: 047c04f7b63a426b11c767c314399ad9c63cf683 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { HookType } from '../../models/plugins/hook-type.enum'
import { isCatchable, isPromise } from '../miscs/miscs'

function getHookType (hookName: string) {
  if (hookName.startsWith('filter:')) return HookType.FILTER
  if (hookName.startsWith('action:')) return HookType.ACTION

  return HookType.STATIC
}

async function internalRunHook (handler: Function, hookType: HookType, param: any, onError: (err: Error) => void) {
  let result = param

  try {
    const p = handler(result)

    switch (hookType) {
      case HookType.FILTER:
        if (isPromise(p)) result = await p
        else result = p
        break

      case HookType.STATIC:
        if (isPromise(p)) await p
        break

      case HookType.ACTION:
        if (isCatchable(p)) p.catch(err => onError(err))
        break
    }
  } catch (err) {
    onError(err)
  }

  return result
}

export {
  getHookType,
  internalRunHook
}