import ApplicationComponent from "../ApplicationComponent"; import {NextFunction, Request, Response, Router} from "express"; import {ServiceUnavailableHttpError} from "../HttpError"; import Application from "../Application"; import config from "config"; export default class MaintenanceComponent extends ApplicationComponent { private readonly application: Application; private readonly canServe: () => boolean; public constructor(application: Application, canServe: () => boolean) { super(); this.application = application; this.canServe = canServe; } public async handle(router: Router): Promise { 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; throw new ServiceUnavailableHttpError(`${config.get('app.name')} is readying up. Please wait a few seconds...`); } if (!this.canServe()) { res.locals.refresh_after = 30; throw new ServiceUnavailableHttpError(`${config.get('app.name')} is unavailable due to failure of dependent services.`); } next(); }); } }