Make it possible to supply hook data with reload

This commit is contained in:
Jan Oberhauser 2020-12-30 11:45:29 +01:00
parent 8ada4534ec
commit ed1f29feba
2 changed files with 32 additions and 16 deletions

View file

@ -1,6 +1,7 @@
import { import {
Db, Db,
IExternalHooksClass, IExternalHooksClass,
IExternalHooksFileData,
IExternalHooksFunctions, IExternalHooksFunctions,
} from './'; } from './';
@ -26,9 +27,14 @@ class ExternalHooksClass implements IExternalHooksClass {
} }
async reload() { async reload(externalHooks?: IExternalHooksFileData) {
this.externalHooks = {}; this.externalHooks = {};
if (externalHooks === undefined) {
await this.loadHooksFiles(true); await this.loadHooksFiles(true);
} else {
this.loadHooks(externalHooks);
}
} }
@ -45,10 +51,19 @@ class ExternalHooksClass implements IExternalHooksClass {
delete require.cache[require.resolve(hookFilePath)]; delete require.cache[require.resolve(hookFilePath)];
} }
const hookFile = require(hookFilePath); const hookFile = require(hookFilePath) as IExternalHooksFileData;
this.loadHooks(hookFile);
} catch (error) {
throw new Error(`Problem loading external hook file "${hookFilePath}": ${error.message}`);
}
}
}
}
for (const resource of Object.keys(hookFile)) {
for (const operation of Object.keys(hookFile[resource])) { loadHooks(hookFileData: IExternalHooksFileData) {
for (const resource of Object.keys(hookFileData)) {
for (const operation of Object.keys(hookFileData[resource])) {
// Save all the hook functions directly under their string // Save all the hook functions directly under their string
// format in an array // format in an array
const hookString = `${resource}.${operation}`; const hookString = `${resource}.${operation}`;
@ -56,12 +71,7 @@ class ExternalHooksClass implements IExternalHooksClass {
this.externalHooks[hookString] = []; this.externalHooks[hookString] = [];
} }
this.externalHooks[hookString].push.apply(this.externalHooks[hookString], hookFile[resource][operation]); this.externalHooks[hookString].push.apply(this.externalHooks[hookString], hookFileData[resource][operation]);
}
}
} catch (error) {
throw new Error(`Problem loading external hook file "${hookFilePath}": ${error.message}`);
}
} }
} }
} }

View file

@ -219,6 +219,12 @@ export interface IExternalHooks {
}; };
} }
export interface IExternalHooksFileData {
[key: string]: {
[key: string]: Array<(...args: any[]) => Promise<void>>; //tslint:disable-line:no-any
};
}
export interface IExternalHooksFunctions { export interface IExternalHooksFunctions {
dbCollections: IDatabaseCollections; dbCollections: IDatabaseCollections;
} }