2019-07-18 14:28:37 +02:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2019-07-22 11:18:22 +02:00
|
|
|
async function internalRunHook <T> (handler: Function, hookType: HookType, result: T, params: any, onError: (err: Error) => void) {
|
2019-07-18 14:28:37 +02:00
|
|
|
try {
|
2019-07-19 17:30:41 +02:00
|
|
|
if (hookType === HookType.FILTER) {
|
|
|
|
const p = handler(result, params)
|
|
|
|
|
|
|
|
if (isPromise(p)) result = await p
|
|
|
|
else result = p
|
|
|
|
|
|
|
|
return result
|
|
|
|
}
|
2019-07-18 14:28:37 +02:00
|
|
|
|
2019-07-19 17:30:41 +02:00
|
|
|
// Action/static hooks do not have result value
|
|
|
|
const p = handler(params)
|
|
|
|
|
|
|
|
if (hookType === HookType.STATIC) {
|
|
|
|
if (isPromise(p)) await p
|
|
|
|
|
|
|
|
return undefined
|
|
|
|
}
|
2019-07-18 14:28:37 +02:00
|
|
|
|
2019-07-19 17:30:41 +02:00
|
|
|
if (hookType === HookType.ACTION) {
|
2019-07-22 15:40:13 +02:00
|
|
|
if (isCatchable(p)) p.catch((err: any) => onError(err))
|
2019-07-18 14:28:37 +02:00
|
|
|
|
2019-07-19 17:30:41 +02:00
|
|
|
return undefined
|
2019-07-18 14:28:37 +02:00
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
onError(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
|
|
|
export {
|
|
|
|
getHookType,
|
|
|
|
internalRunHook
|
|
|
|
}
|