Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/modules/health/health.controllers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
import { Request, Response } from 'express';
import { prisma } from '../../utils/prisma.utils';
import { envConfig } from '../../config';
import { PUBLIC_ENDPOINT_CACHE_SECONDS } from '../../constants/public-endpoint-cache.constants';

type CheckStatus = 'ok' | 'fail';

interface ReadinessCheck {
name: string;
status: CheckStatus;
latencyMs?: number;
error?: string;
}

interface HealthStatus {
success: boolean;
Expand Down Expand Up @@ -105,3 +115,40 @@ export const simpleHealthCheck = (_: Request, res: Response): void => {
timestamp: new Date().toISOString(),
});
};

export const readinessCheck = async (_: Request, res: Response): Promise<void> => {
const checks: ReadinessCheck[] = [];

// DB check
const dbStart = Date.now();
try {
await prisma.$queryRaw`SELECT 1`;
checks.push({ name: 'database', status: 'ok', latencyMs: Date.now() - dbStart });
} catch (err) {
checks.push({
name: 'database',
status: 'fail',
error: err instanceof Error ? err.message : 'Unknown error',
});
}

// Cache config check — verifies the HTTP cache layer is configured
try {
const configured = typeof PUBLIC_ENDPOINT_CACHE_SECONDS.short === 'number';
if (!configured) throw new Error('Cache config unavailable');
checks.push({ name: 'cache', status: 'ok' });
} catch (err) {
checks.push({
name: 'cache',
status: 'fail',
error: err instanceof Error ? err.message : 'Unknown error',
});
}

const ready = checks.every(c => c.status === 'ok');
res.status(ready ? 200 : 503).json({
ready,
timestamp: new Date().toISOString(),
checks,
});
};
13 changes: 8 additions & 5 deletions src/modules/health/health.routes.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { Router } from 'express';
import { healthCheck, simpleHealthCheck } from './health.controllers';
import { healthCheck, simpleHealthCheck, readinessCheck } from './health.controllers';

const router = Router();

// Detailed health check with database connectivity
router.get('/detailed', healthCheck);

// Simple health check for load balancers
// Liveness — simple check for load balancers, no dependency probing
router.get('/', simpleHealthCheck);

// Readiness — checks DB and cache; returns 503 if any critical dep is unavailable
router.get('/ready', readinessCheck);

// Detailed — full diagnostics including memory, system, and db response time
router.get('/detailed', healthCheck);

export default router;
Loading