All files / src Hook.ts

67.37% Statements 64/95
61.76% Branches 21/34
54.05% Functions 20/37
67.02% Lines 63/94

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 23915x     15x                                                 69x 69x 69x 69x   69x   25x 25x 25x 25x   69x   69x   15x 15x 15x 15x   69x   69x   12x 12x 12x 12x   69x       52x 1x 2x   1x 1x                                                           52x               110x 110x 110x       106x 106x 1x   106x       106x         106x 95x 11x     11x     11x   11x 6x 6x     11x     106x               37x       44x       25x       4x   4x       3x   3x 3x                                             4x   4x             4x       35x       35x 8x                                                 15x  
import { deprecate } from './utils'
 
// tslint:disable-next-line:no-empty
const deprecateContext = deprecate(() => {}, 'Hook.context is deprecated and will be removed')
 
class Hook {
    // use to cache origin call func
    public _call: (...args: any[]) => any
    // use to cache call tap func
    public call: (...args: any[]) => any
    // use to cache origin call func
    public _callAsync: (...args: any[]) => any
    // use to cache call tapAsync func
    public callAsync: (...args: any[]) => any
    // use to cache origin call func
    public _promise: (...args: any[]) => Promise<any>
    // use to cache call tapPromise func
    public promise: (...args: any[]) => Promise<any>
    // use to cache arguments for tap function
    private _args: string[]
    // use to cache hook's name
    private name: string
    // use to cache taps function
    private taps: HooksTapsItem[]
    // if hooks has once tap
    private once: boolean
 
    constructor(args: string[], name?: string) {
        this._args = args || []
        this.name = name || ''
        this.taps = []
        this.once = false
 
        this._call = function (..._args: any[]) {
            // @ts-ignore
            this.call = this._createCall('sync')
            const res = this.call(..._args)
            this.afterInvoke()
            return res
        }
        this.call = this._call
 
        this._callAsync = function (..._args: any[]) {
            // @ts-ignore
            this.callAsync = this._createCall('async')
            const res = this.callAsync(..._args)
            this.afterInvoke()
            return res
        }
        this.callAsync = this._callAsync
 
        this._promise = function (..._args: any[]) {
            // @ts-ignore
            this.promise = this._createCall('promise')
            const res = this.promise(..._args)
            this.afterInvoke()
            return res
        }
        this.promise = this._promise
    }
 
    afterInvoke() {
        if (this.once) {
            this.taps = this.taps.filter((item) => {
                return !item.once
            })
            this._resetCompilation()
            this.once = false
        }
    }
 
    // this function is Abstract to Hooks Class
    // @ts-ignore
    compile(options: HookCompileOptions) {
        throw new Error('Abstract: should be overridden')
    }
 
    isUsed() {
        return this.taps.length > 0
    }
 
    withOptions(options: UserTapOptions) {
        const mergeOptions = (opt: UserTapOptions): UserTapOptions =>
            Object.assign({}, options, typeof opt === 'string' ? { name: opt } : opt)
 
        return {
            name: this.name,
            tap: (opt: UserTapOptions, fn: () => any) => this.tap(mergeOptions(opt), fn),
            tapAsync: (opt: UserTapOptions, fn: () => any) => this.tapAsync(mergeOptions(opt), fn),
            tapPromise: (opt: UserTapOptions, fn: () => any) =>
                this.tapPromise(mergeOptions(opt), fn),
            isUsed: () => this.isUsed(),
            withOptions: (opt: UserTapOptions) => this.withOptions(mergeOptions(opt))
        }
    }
 
    _createCall(type: Types) {
        return this.compile({
            taps: this.taps,
            args: this._args,
            type
        })
    }
 
    _resetCompilation() {
        this.call = this._call
        this.callAsync = this._callAsync
        this.promise = this._promise
    }
 
    _insert(item: HooksTapsItem) {
        this._resetCompilation()
        if (!this.once && item.once) {
            this.once = true
        }
        this.taps.push(item)
    }
 
    _tap(type: Types, options: UserTapOptions, fn: (...args: any[]) => any) {
        const tapOptions = {
            name: '',
            context: false,
            once: false
        }
        if (typeof options === 'string') {
            tapOptions.name = options.trim()
        } else Iif (typeof options !== 'object' || options === null) {
            throw new Error('Invalid tap options')
        } else {
            Iif (typeof options.name !== 'string' || options.name === '') {
                throw new Error('Missing name for tap')
            } else {
                tapOptions.name = options.name
            }
            if (options.context) {
                deprecateContext()
                tapOptions.context = options.context
            }
 
            tapOptions.once = Boolean(options.once)
        }
 
        this._insert({
            type,
            fn,
            ...tapOptions
        })
    }
 
    tap(options: UserTapOptions, fn: (...args: any[]) => any) {
        this._tap('sync', options, fn)
    }
 
    tapAsync(options: UserTapOptions, fn: (...args: any[]) => any) {
        this._tap('async', options, fn)
    }
 
    tapPromise(options: UserTapOptions, fn: (...args: any[]) => any) {
        this._tap('promise', options, fn)
    }
 
    _isRegistered(type: Types, fn: (...args: []) => any): boolean {
        const index = this._tapHookIndexOf(type, fn)
 
        return index !== -1
    }
 
    _deleteTapHook(type: Types, fn: (...args: []) => any): void {
        this._resetCompilation()
 
        this.taps = this.taps.filter((tap) => {
            return !(tap.type === type && tap.fn === fn)
        })
    }
 
    _replaceTapHook(
        type: Types,
        oldFn: (...args: any[]) => any,
        newFn: (...args: []) => any
    ): boolean {
        this._resetCompilation()
 
        let replaced = false
        for (const tap of this.taps) {
            if (tap.type === type && tap.fn === oldFn) {
                replaced = true
                tap.fn = newFn
            }
        }
 
        return replaced
    }
 
    _tapHookIndexOf(type: Types, fn: (...args: []) => any): number {
        let index = -1
 
        for (let _index = 0; _index < this.taps.length; _index++) {
            if (this.taps[_index].fn === fn && this.taps[_index].type === type) {
                index = _index
                break
            }
        }
 
        return index
    }
 
    forbiddenCall() {
        this.call = () => {
            throw new Error(`call is not supported on a ${this.name}`)
        }
 
        this._call = () => {
            throw new Error(`call is not supported on a ${this.name}`)
        }
    }
 
    forbiddenCallAsync() {
        this.callAsync = () => {
            throw new Error(`callAsync is not supported on a ${this.name}`)
        }
 
        this._callAsync = () => {
            throw new Error(`callAsync is not supported on a ${this.name}`)
        }
    }
 
    forbiddenPromise() {
        this.promise = () => {
            throw new Error(`promise is not supported on a ${this.name}`)
        }
 
        this._promise = () => {
            throw new Error(`promise is not supported on a ${this.name}`)
        }
    }
}
 
export default Hook