保誠-保戶業務員媒合平台
HelenHuang
2022-06-09 9bdb95c9e34cef640534e5e5a1e2225a80442000
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { serial, flatHooks } from './utils'
 
export default class Hookable {
  constructor (logger = console) {
    this._logger = logger
    this._hooks = {}
    this._deprecatedHooks = {}
 
    // Allow destructuring hook and callHook functions out of instance object
    this.hook = this.hook.bind(this)
    this.callHook = this.callHook.bind(this)
  }
 
  hook (name, fn) {
    if (!name || typeof fn !== 'function') {
      return
    }
 
    const originalName = name
    let deprecatedHook
    while (this._deprecatedHooks[name]) {
      deprecatedHook = this._deprecatedHooks[name]
      if (typeof deprecatedHook === 'string') {
        deprecatedHook = { to: deprecatedHook }
      }
      name = deprecatedHook.to
    }
    if (deprecatedHook) {
      if (!deprecatedHook.message) {
        this._logger.warn(
          `${originalName} hook has been deprecated` +
          (deprecatedHook.to ? `, please use ${deprecatedHook.to}` : '')
        )
      } else {
        this._logger.warn(deprecatedHook.message)
      }
    }
 
    this._hooks[name] = this._hooks[name] || []
    this._hooks[name].push(fn)
  }
 
  deprecateHook (old, name) {
    this._deprecatedHooks[old] = name
  }
 
  deprecateHooks (deprecatedHooks) {
    Object.assign(this._deprecatedHooks, deprecatedHooks)
  }
 
  addHooks (configHooks) {
    const hooks = flatHooks(configHooks)
    for (const key in hooks) {
      this.hook(key, hooks[key])
    }
  }
 
  async callHook (name, ...args) {
    if (!this._hooks[name]) {
      return
    }
    try {
      await serial(this._hooks[name], fn => fn(...args))
    } catch (err) {
      if (name !== 'error') {
        await this.callHook('error', err)
      }
      if (this._logger.fatal) {
        this._logger.fatal(err)
      } else {
        this._logger.error(err)
      }
    }
  }
 
  clearHook (name) {
    if (name) {
      delete this._hooks[name]
    }
  }
 
  clearHooks () {
    this._hooks = {}
  }
}