diff --git a/src/daily-do-it.ts b/src/daily-do-it.ts index ff4f220..cd65f53 100644 --- a/src/daily-do-it.ts +++ b/src/daily-do-it.ts @@ -23,6 +23,7 @@ import { import { configureHandlebars } from "./helpers/configure-handlebars.js"; import { configureProxySupport } from "./helpers/proxy.js"; import { configureErrorMonitoring } from "./helpers/configure-error-monitoring.js"; +import { dbConnectionTest } from "./middleware/db-connection-test.js"; configureErrorMonitoring(); @@ -38,6 +39,7 @@ app.use(Sentry.Handlers.requestHandler()); app.use( express.static(fileURLToPath(new URL(".", import.meta.url) + "public")), ); +app.use(dbConnectionTest); app.use(sessionMiddleware); app.use(passport.session()); app.use(helmetMiddleware); diff --git a/src/lib/db.ts b/src/lib/db.ts index a2e7df9..6daaa49 100644 --- a/src/lib/db.ts +++ b/src/lib/db.ts @@ -8,3 +8,7 @@ export const pool = new pg.Pool({ password: ENV.DB_PASSWORD, port: ENV.DB_PORT, }); + +pool.on("error", (err) => { + console.error(err); +}); diff --git a/src/middleware/db-connection-test.ts b/src/middleware/db-connection-test.ts new file mode 100644 index 0000000..0e347f5 --- /dev/null +++ b/src/middleware/db-connection-test.ts @@ -0,0 +1,20 @@ +import type { Request, Response, NextFunction } from "express"; +import { pool } from "../lib/db.js"; + +/** + * A Simple database connection checker middleware, tests the + * database can be connected to and handles connection errors. + */ +export async function dbConnectionTest( + req: Request<{}, {}, {}, { async?: "true" | "false" }>, + res: Response, + next: NextFunction, +) { + try { + const connection = await pool.connect(); + connection.release(); + next(); + } catch { + next(new Error("Unable to connect to Database")); + } +}