2020-04-22 15:52:17 +02:00
|
|
|
import ApplicationComponent from "../ApplicationComponent";
|
2020-07-11 11:46:16 +02:00
|
|
|
import {NextFunction, Request, Response, Router} from "express";
|
2020-04-22 15:52:17 +02:00
|
|
|
import {ServiceUnavailableHttpError} from "../HttpError";
|
|
|
|
import Application from "../Application";
|
2020-06-27 18:06:39 +02:00
|
|
|
import config from "config";
|
2020-04-22 15:52:17 +02:00
|
|
|
|
|
|
|
export default class MaintenanceComponent extends ApplicationComponent<void> {
|
|
|
|
private readonly application: Application;
|
|
|
|
private readonly canServe: () => boolean;
|
|
|
|
|
|
|
|
constructor(application: Application, canServe: () => boolean) {
|
|
|
|
super();
|
|
|
|
this.application = application;
|
|
|
|
this.canServe = canServe;
|
|
|
|
}
|
|
|
|
|
2020-07-11 11:46:16 +02:00
|
|
|
public async handle(router: Router): Promise<void> {
|
2020-04-22 15:52:17 +02:00
|
|
|
router.use((req: Request, res: Response, next: NextFunction) => {
|
|
|
|
if (res.headersSent) {
|
|
|
|
return next();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!this.application.isReady()) {
|
|
|
|
res.header({'Retry-After': 60});
|
|
|
|
res.locals.refresh_after = 5;
|
2020-06-27 18:06:39 +02:00
|
|
|
throw new ServiceUnavailableHttpError(`${config.get('app.name')} is readying up. Please wait a few seconds...`);
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if (!this.canServe()) {
|
|
|
|
res.locals.refresh_after = 30;
|
2020-06-27 18:06:39 +02:00
|
|
|
throw new ServiceUnavailableHttpError(`${config.get('app.name')} is unavailable due to failure of dependent services.`);
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
next();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|