From b4055e1c23eeefb0c8a85a77f312b2827d98f483 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 18 Jul 2019 14:28:37 +0200 Subject: Add server hooks --- shared/core-utils/plugins/hooks.ts | 41 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 shared/core-utils/plugins/hooks.ts (limited to 'shared/core-utils/plugins/hooks.ts') diff --git a/shared/core-utils/plugins/hooks.ts b/shared/core-utils/plugins/hooks.ts new file mode 100644 index 000000000..047c04f7b --- /dev/null +++ b/shared/core-utils/plugins/hooks.ts @@ -0,0 +1,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 +} -- cgit v1.2.3