swaf/src/components/MaintenanceComponent.ts

37 lines
1.3 KiB
TypeScript
Raw Normal View History

2020-04-22 15:52:17 +02:00
import ApplicationComponent from "../ApplicationComponent";
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;
}
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();
});
}
}