40 lines
1.4 KiB
TypeScript
40 lines
1.4 KiB
TypeScript
|
import ApplicationComponent from "../ApplicationComponent";
|
||
|
import {Express, NextFunction, Request, Response, Router} from "express";
|
||
|
import {ServiceUnavailableHttpError} from "../HttpError";
|
||
|
import Application from "../Application";
|
||
|
|
||
|
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 start(app: Express, router: Router): Promise<void> {
|
||
|
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('Watch My Stream is readying up. Please wait a few seconds...');
|
||
|
}
|
||
|
|
||
|
if (!this.canServe()) {
|
||
|
res.locals.refresh_after = 30;
|
||
|
throw new ServiceUnavailableHttpError('Watch My Stream is unavailable due to failure of dependent services.');
|
||
|
}
|
||
|
|
||
|
next();
|
||
|
});
|
||
|
}
|
||
|
|
||
|
public async stop(): Promise<void> {
|
||
|
}
|
||
|
|
||
|
}
|