From 21650994d2aaf713fdca9bcb0d8e21fbb17f133e Mon Sep 17 00:00:00 2001 From: Dessa Simpson Date: Sun, 29 Nov 2020 13:30:27 -0700 Subject: [PATCH] Implement checkVersion middleware Checks version on each request, terminating the application if version mdoes not match --- src/app.ts | 8 +++++++- src/version.ts | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/app.ts b/src/app.ts index dc50ec8..494aae9 100644 --- a/src/app.ts +++ b/src/app.ts @@ -8,6 +8,7 @@ import session from "express-session"; import pg from "pg"; import pgSessionStore from "connect-pg-simple"; import fetch, { Response as FetchResponse } from "node-fetch"; +import { log, LogLevel } from "./logging" import cron from "./cron"; import db from "./db"; import errorHandler from "./errors"; @@ -26,6 +27,7 @@ async function validateApiToken(session: Express.Session) { } const app = express(); +app.use(version.checkVersionMiddleware); app.use(express.static('public')); app.use(express.urlencoded({extended: false})); app.use(session({ @@ -340,4 +342,8 @@ version.checkVersion().then(_ => app.listen(config.port, () => { cron.run(); setInterval(cron.run,config.cronInterval); console.log(`Listening on port ${config.port}`); -})); +})) +.catch((e) => { + log(LogLevel.ERROR,e) + process.exit(1); +}); diff --git a/src/version.ts b/src/version.ts index cfe9591..434c3bd 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,4 +1,6 @@ import * as queries from "./queries"; +import { log, LogLevel } from "./logging" +import express from "express"; import pg from "pg"; import db from "./db"; @@ -10,6 +12,19 @@ export function getVersion() { return `${versionMajor}.${versionMinor}.${versionPatch}` } +export async function checkVersionMiddleware(_req: express.Request, _res: express.Response, next: express.NextFunction) { + try { + await checkVersion(); + } catch (e) { + log(LogLevel.ERROR,e) + // Terminate the nodejs process with error. If restarted, the app will + // never start listening for new requests so this will not result in a + // restart loop. + process.exit(1); + } + next(); +} + export async function checkVersion() { var dbver = await db.query(queries.getDbVersion).then((result: pg.QueryResult) => result.rows[0]['get_version']); if (dbver != `${versionMajor}.${versionMinor}`) {