UNPKG

1.53 kBPlain TextView Raw
1import { RealmType, Realm } from "./realm";
2import * as awsHooks from './hook-aws';
3import * as gcpHooks from './hook-gcp';
4
5
6type HookFn = (realm: Realm, ...args: any[]) => Promise<any>;
7type HookName = 'dpush_prep' | 'dpush_image_ex' | 'realm_init' | 'realm_set_begin' | 'realm_check';
8
9const hooksDic: Map<RealmType, Map<HookName, HookFn>> = new Map();
10
11type FnByHookName = { [name: string]: HookFn };
12
13//#region ---------- Initialize the Hook Registry ----------
14const hookObjByType = {
15 'aws': awsHooks as FnByHookName,
16 'gcp': gcpHooks as FnByHookName
17};
18
19for (const k of Object.keys(hookObjByType)) {
20 const type = k as 'aws' | 'gcp'; // Note: might have a better way to get types from hookObjByType
21 const fnByName = hookObjByType[type];
22 for (const key in fnByName) {
23 // TODO: need some validations
24 const name = key as HookName;
25 const fn = fnByName[name] as HookFn;
26 registerHook(type, name, fn);
27 }
28}
29
30//#endregion ---------- /Initialize the Hook Registry ----------
31
32export async function callHook(realm: Realm, name: HookName, ...args: any[]) {
33 const fn = getHook(realm.type, name);
34 if (fn) {
35 return fn(realm, ...args);
36 }
37}
38
39function getHook(type: RealmType, name: HookName): HookFn | undefined {
40 const fnDic = hooksDic.get(type);
41 return (fnDic) ? fnDic.get(name) : undefined;
42}
43
44function registerHook(type: RealmType, name: HookName, fn: HookFn) {
45 let fnDic = hooksDic.get(type);
46 if (fnDic == null) {
47 fnDic = new Map<HookName, HookFn>();
48 hooksDic.set(type, fnDic);
49 }
50 fnDic.set(name, fn);
51}
52