| 1 | import { MongoClient } from 'mongodb'; |
| 2 | |
| 3 | import { env } from '@/config/env'; |
| 4 | import { logger } from '@/utils/logger'; |
| 5 | |
| 6 | let client: MongoClient | null = null; |
| 7 | |
| 8 | export const getMongoClient = async (): Promise<MongoClient> => { |
| 9 | if (client) { |
| 10 | return client; |
| 11 | } |
| 12 | |
| 13 | const mongoUrl = env.MONGO_URL; |
| 14 | client = new MongoClient(mongoUrl); |
| 15 | await client.connect(); |
| 16 | logger.info('MongoDB connection established'); |
| 17 | |
| 18 | return client; |
| 19 | }; |
| 20 | |
| 21 | export const closeMongoClient = async () => { |
| 22 | if (!client) { |
| 23 | return; |
| 24 | } |
| 25 | await client.close(); |
| 26 | logger.info('MongoDB connection closed'); |
| 27 | client = null; |
| 28 | }; |