Thin MongoDB ODM built for Standard Schema
mongodb zod deno
1import { type Db, type MongoClientOptions, MongoClient } from "mongodb"; 2 3interface Connection { 4 client: MongoClient; 5 db: Db; 6} 7 8let connection: Connection | null = null; 9 10export interface ConnectOptions extends MongoClientOptions {}; 11 12/** 13 * Health check details of the MongoDB connection 14 * 15 * @property healthy - Overall health status of the connection 16 * @property connected - Whether a connection is established 17 * @property responseTimeMs - Response time in milliseconds (if connection is healthy) 18 * @property error - Error message if health check failed 19 * @property timestamp - Timestamp when health check was performed 20 */ 21export interface HealthCheckResult { 22 healthy: boolean; 23 connected: boolean; 24 responseTimeMs?: number; 25 error?: string; 26 timestamp: Date; 27} 28 29/** 30 * Connect to MongoDB with options including connection pooling 31 * 32 * @param uri - MongoDB connection string 33 * @param dbName - Name of the database to connect to 34 * @param options - Connection options including connection pooling 35 * 36 * @example 37 * ```ts 38 * await connect("mongodb://localhost:27017", "mydb", { 39 * maxPoolSize: 10, 40 * minPoolSize: 2, 41 * maxIdleTimeMS: 30000, 42 * connectTimeoutMS: 10000, 43 * socketTimeoutMS: 45000, 44 * }); 45 * ``` 46 */ 47export async function connect( 48 uri: string, 49 dbName: string, 50 options?: ConnectOptions, 51): Promise<Connection> { 52 if (connection) { 53 return connection; 54 } 55 56 const client = new MongoClient(uri, options); 57 await client.connect(); 58 const db = client.db(dbName); 59 60 connection = { client, db }; 61 return connection; 62} 63 64export async function disconnect(): Promise<void> { 65 if (connection) { 66 await connection.client.close(); 67 connection = null; 68 } 69} 70 71export function getDb(): Db { 72 if (!connection) { 73 throw new Error("MongoDB not connected. Call connect() first."); 74 } 75 return connection.db; 76} 77 78/** 79 * Check the health of the MongoDB connection 80 * 81 * Performs a ping operation to verify the database is responsive 82 * and returns detailed health information including response time. 83 * 84 * @example 85 * ```ts 86 * const health = await healthCheck(); 87 * if (health.healthy) { 88 * console.log(`Database healthy (${health.responseTimeMs}ms)`); 89 * } else { 90 * console.error(`Database unhealthy: ${health.error}`); 91 * } 92 * ``` 93 */ 94export async function healthCheck(): Promise<HealthCheckResult> { 95 const timestamp = new Date(); 96 97 // Check if connection exists 98 if (!connection) { 99 return { 100 healthy: false, 101 connected: false, 102 error: "No active connection. Call connect() first.", 103 timestamp, 104 }; 105 } 106 107 try { 108 // Measure ping response time 109 const startTime = performance.now(); 110 await connection.db.admin().ping(); 111 const endTime = performance.now(); 112 const responseTimeMs = Math.round(endTime - startTime); 113 114 return { 115 healthy: true, 116 connected: true, 117 responseTimeMs, 118 timestamp, 119 }; 120 } catch (error) { 121 return { 122 healthy: false, 123 connected: true, 124 error: error instanceof Error ? error.message : String(error), 125 timestamp, 126 }; 127 } 128}