Skip to content

Commit

Permalink
Add middleware to check database connection, handle errors from conne…
Browse files Browse the repository at this point in the history
…ction pool
  • Loading branch information
ollieri3 committed Mar 27, 2024
1 parent f66e8a9 commit 9a2c9d1
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/daily-do-it.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand All @@ -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);
Expand Down
4 changes: 4 additions & 0 deletions src/lib/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
20 changes: 20 additions & 0 deletions src/middleware/db-connection-test.ts
Original file line number Diff line number Diff line change
@@ -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"));
}
}

0 comments on commit 9a2c9d1

Please sign in to comment.