UNPKG

@thalorlabs/database

Version:

Database utilities and connection helpers for TypeScript applications with MongoDB support

53 lines (52 loc) 1.89 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.mongoDBConnect = mongoDBConnect; const mongoose_1 = __importDefault(require("mongoose")); /** * Establishes a MongoDB connection with optional caching. * Returns the existing connection if caching is enabled and already connected. * * @param uri - MongoDB connection URI * @param options - MongoDB connection options including caching behavior * @returns Promise resolving to Mongoose instance * @throws Error if connection fails * * @example * const connection = await mongoDBConnect( * 'mongodb://localhost:27017/myapp', * { maxPoolSize: 10, useCache: true } * ); * * @example * const connection = await mongoDBConnect(process.env.MONGO_URI!); * * @example * // Force new connection every time * const connection = await mongoDBConnect(uri, { useCache: false }); */ async function mongoDBConnect(uri, options) { const { useCache = true, ...connectOptions } = options || {}; // If caching is disabled, always create a new connection if (!useCache) { try { return await mongoose_1.default.connect(uri, connectOptions); } catch (error) { throw new Error(`Failed to connect to MongoDB: ${error instanceof Error ? error.message : 'Unknown error'}`); } } // Check if we already have a cached connection if (mongoose_1.default.connection.readyState === 1) { return mongoose_1.default; } try { const connection = await mongoose_1.default.connect(uri, connectOptions); return connection; } catch (error) { throw new Error(`Failed to connect to MongoDB: ${error instanceof Error ? error.message : 'Unknown error'}`); } }