diff --git a/src/routes/health.js b/src/routes/health.js new file mode 100644 index 0000000..a8ed13c --- /dev/null +++ b/src/routes/health.js @@ -0,0 +1,13 @@ +import logger from '../utils/logger.js'; +import { db } from '../db/index.js'; +import { sql } from 'drizzle-orm'; + +export const handleHealth = async (req) => { + try { + await db.execute(sql`SELECT 1`); + return Response.json({ status: 'ok' }, { status: 200 }); + } catch (error) { + logger.error('Health check failed', { error: error.message }); + return Response.json({ status: 'error', error: error.message }, { status: 500 }); + } +}; diff --git a/test/health.test.js b/test/health.test.js new file mode 100644 index 0000000..7b901a6 --- /dev/null +++ b/test/health.test.js @@ -0,0 +1,41 @@ +import { describe, it, expect, mock, beforeEach } from "bun:test"; + +// Mock database layer +const mockExecute = mock(() => Promise.resolve()); + +mock.module("../src/db/index.js", () => ({ + db: { + execute: mockExecute + } +})); + +describe("Health Route Handler", () => { + let handleHealth; + + beforeEach(async () => { + mockExecute.mockClear(); + const healthRoute = await import("../src/routes/health.js"); + handleHealth = healthRoute.handleHealth; + }); + + it("should return status 200 and ok when DB is healthy", async () => { + const req = new Request("http://localhost:3000/health"); + const res = await handleHealth(req); + + expect(res.status).toBe(200); + const body = await res.json(); + expect(body).toEqual({ status: "ok" }); + expect(mockExecute).toHaveBeenCalled(); + }); + + it("should return status 500 and error details when DB health check fails", async () => { + mockExecute.mockImplementationOnce(() => Promise.reject(new Error("DB Connection Failed"))); + const req = new Request("http://localhost:3000/health"); + const res = await handleHealth(req); + + expect(res.status).toBe(500); + const body = await res.json(); + expect(body.status).toBe("error"); + expect(body.error).toBe("DB Connection Failed"); + }); +});