Thin MongoDB ODM built for Standard Schema
mongodb
zod
deno
1import { getConnection } from "./connection.ts";
2
3/**
4 * Health check module
5 *
6 * Provides functionality for monitoring MongoDB connection health
7 * including ping operations and response time measurement.
8 */
9
10/**
11 * Health check details of the MongoDB connection
12 *
13 * @property healthy - Overall health status of the connection
14 * @property connected - Whether a connection is established
15 * @property responseTimeMs - Response time in milliseconds (if connection is healthy)
16 * @property error - Error message if health check failed
17 * @property timestamp - Timestamp when health check was performed
18 */
19export interface HealthCheckResult {
20 healthy: boolean;
21 connected: boolean;
22 responseTimeMs?: number;
23 error?: string;
24 timestamp: Date;
25}
26
27/**
28 * Check the health of the MongoDB connection
29 *
30 * Performs a ping operation to verify the database is responsive
31 * and returns detailed health information including response time.
32 *
33 * @returns Health check result with status and metrics
34 *
35 * @example
36 * ```ts
37 * const health = await healthCheck();
38 * if (health.healthy) {
39 * console.log(`Database healthy (${health.responseTimeMs}ms)`);
40 * } else {
41 * console.error(`Database unhealthy: ${health.error}`);
42 * }
43 * ```
44 */
45export async function healthCheck(): Promise<HealthCheckResult> {
46 const timestamp = new Date();
47 const connection = getConnection();
48
49 // Check if connection exists
50 if (!connection) {
51 return {
52 healthy: false,
53 connected: false,
54 error: "No active connection. Call connect() first.",
55 timestamp,
56 };
57 }
58
59 try {
60 // Measure ping response time
61 const startTime = performance.now();
62 await connection.db.admin().ping();
63 const endTime = performance.now();
64 const responseTimeMs = Math.round(endTime - startTime);
65
66 return {
67 healthy: true,
68 connected: true,
69 responseTimeMs,
70 timestamp,
71 };
72 } catch (error) {
73 return {
74 healthy: false,
75 connected: true,
76 error: error instanceof Error ? error.message : String(error),
77 timestamp,
78 };
79 }
80}