2020-04-22 15:52:17 +02:00
|
|
|
import {Express, Router} from "express";
|
|
|
|
import Logger from "./Logger";
|
|
|
|
import {sleep} from "./Utils";
|
2020-04-25 09:34:02 +02:00
|
|
|
import Application from "./Application";
|
2020-04-22 15:52:17 +02:00
|
|
|
|
|
|
|
export default abstract class ApplicationComponent<T> {
|
|
|
|
private val?: T;
|
2020-04-25 09:34:02 +02:00
|
|
|
protected app?: Application;
|
2020-04-22 15:52:17 +02:00
|
|
|
|
2020-07-11 11:46:16 +02:00
|
|
|
public async start(app: Express): Promise<void> {
|
|
|
|
}
|
|
|
|
|
|
|
|
public async init(router: Router): Promise<void> {
|
|
|
|
}
|
2020-04-22 15:52:17 +02:00
|
|
|
|
2020-07-11 11:46:16 +02:00
|
|
|
public async handle(router: Router): Promise<void> {
|
|
|
|
}
|
|
|
|
|
|
|
|
public async stop(): Promise<void> {
|
|
|
|
|
|
|
|
}
|
2020-04-22 15:52:17 +02:00
|
|
|
|
|
|
|
protected export(val: T) {
|
|
|
|
this.val = val;
|
|
|
|
}
|
|
|
|
|
|
|
|
public import(): T {
|
|
|
|
if (!this.val) throw 'Cannot import if nothing was exported.';
|
|
|
|
return this.val;
|
|
|
|
}
|
|
|
|
|
2020-04-25 09:34:02 +02:00
|
|
|
public setApp(app: Application) {
|
|
|
|
this.app = app;
|
|
|
|
}
|
|
|
|
|
2020-04-22 15:52:17 +02:00
|
|
|
protected async prepare(name: string, prepare: () => Promise<void>): Promise<void> {
|
|
|
|
let err;
|
|
|
|
do {
|
|
|
|
try {
|
|
|
|
await prepare();
|
|
|
|
err = null;
|
|
|
|
} catch (e) {
|
|
|
|
err = e;
|
|
|
|
Logger.error(err, `${name} failed to prepare; retrying in 5s...`)
|
|
|
|
await sleep(5000);
|
|
|
|
}
|
|
|
|
} while (err);
|
|
|
|
Logger.info(`${name} ready!`);
|
|
|
|
}
|
|
|
|
|
|
|
|
protected async close(thingName: string, thing: any, fn: Function): Promise<void> {
|
|
|
|
try {
|
|
|
|
await new Promise((resolve, reject) => fn.call(thing, (err: any) => {
|
|
|
|
if (err) reject(err);
|
|
|
|
else resolve();
|
|
|
|
}));
|
|
|
|
|
|
|
|
Logger.info(`${thingName} closed.`);
|
|
|
|
} catch (e) {
|
|
|
|
Logger.error(e, `An error occurred while closing the ${thingName}.`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|