UNPKG

imo-publications-mcp-server

Version:

MCP server for IMO (International Maritime Organization) publications - Node.js TypeScript version

47 lines (46 loc) 1.38 kB
import { MongoClient } from 'mongodb'; import { logger } from './api.js'; let client = null; let db = null; export async function connectToMongoDB(config) { try { if (client && db) { logger.log('Using existing MongoDB connection'); return { client, db }; } logger.log('Connecting to MongoDB...'); client = new MongoClient(config.mongoUri); await client.connect(); db = client.db(config.dbName); logger.log(`Successfully connected to MongoDB database: ${config.dbName}`); return { client, db }; } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error'; logger.error(`Failed to connect to MongoDB: ${errorMessage}`, error); throw new Error(`MongoDB connection failed: ${errorMessage}`); } } export async function getDb(config) { if (!db) { const { db: database } = await connectToMongoDB(config); return database; } return db; } export async function closeMongoDB() { if (client) { await client.close(); client = null; db = null; logger.log('MongoDB connection closed'); } } process.on('SIGINT', async () => { await closeMongoDB(); process.exit(0); }); process.on('SIGTERM', async () => { await closeMongoDB(); process.exit(0); });