aboutsummaryrefslogtreecommitdiffhomepage
path: root/shared/core-utils/plugins/hooks.ts
blob: 3784969b5cba82eaea695714d48c457bbda85620 (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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { HookType } from '../../models/plugins/hook-type.enum'
import { isCatchable, isPromise } from '../common/promises'

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

  return HookType.STATIC
}

async function internalRunHook <T> (options: {
  handler: Function
  hookType: HookType
  result: T
  params: any
  onError: (err: Error) => void
}) {
  const { handler, hookType, result, params, onError } = options

  try {
    if (hookType === HookType.FILTER) {
      const p = handler(result, params)

      const newResult = isPromise(p)
        ? await p
        : p

      return newResult
    }

    // Action/static hooks do not have result value
    const p = handler(params)

    if (hookType === HookType.STATIC) {
      if (isPromise(p)) await p

      return undefined
    }

    if (hookType === HookType.ACTION) {
      if (isCatchable(p)) p.catch((err: any) => onError(err))

      return undefined
    }
  } catch (err) {
    onError(err)
  }

  return result
}

export {
  getHookType,
  internalRunHook
}