UNPKG

@thalorlabs/database

Version:

Database utilities and connection helpers for TypeScript applications with MongoDB support

321 lines (228 loc) 7.09 kB
# @thalorlabs/database A comprehensive database utilities package for TypeScript applications with MongoDB connection management and configuration helpers. ## Installation ```bash npm install @thalorlabs/database ``` ## Features - **MongoDB connection management** with connection caching and reuse - **TypeScript support** with full type safety - **Configurable connection options** for different environments - **Environment-based configuration** with sensible defaults - **Connection pooling** and timeout management - **Error handling** for connection failures ## Quick Start ```typescript import { mongoDBConnect } from '@thalorlabs/database'; // Connect to MongoDB const connection = await mongoDBConnect(); console.log('Connected to MongoDB'); // Use the connection for your operations const db = connection.connection.db; ``` ## Database Connection ### Basic Connection ```typescript import { mongoDBConnect } from '@thalorlabs/database'; // Simple connection const connection = await mongoDBConnect(); ``` ### With Environment Variables ```bash # Set your MongoDB URI export MONGO_URI="mongodb://localhost:27017/your-database" ``` ```typescript import { mongoDBConnect } from '@thalorlabs/database'; // Uses MONGO_URI environment variable const connection = await mongoDBConnect(); ``` ### Custom Connection Options ```typescript import mongoose from 'mongoose'; import { MONGO_URI } from '@thalorlabs/database'; // Custom connection with specific options const connection = await mongoose.connect(MONGO_URI, { maxPoolSize: 20, serverSelectionTimeoutMS: 10000, socketTimeoutMS: 45000, }); ``` ## Configuration ### Environment Variables ```bash # Required: MongoDB connection URI MONGO_URI=mongodb://localhost:27017/your-database # Optional: Environment NODE_ENV=production ``` ### Default Configuration The package provides sensible defaults for MongoDB connections: ```typescript import { DEFAULT_CONNECTION_OPTIONS } from '@thalorlabs/database'; // Default options include: // - bufferCommands: true // - maxPoolSize: 10 // - serverSelectionTimeoutMS: 5000 // - socketTimeoutMS: 45000 // - family: 4 (IPv4) ``` ## Advanced Usage ### Connection Caching The `mongoDBConnect` function automatically caches connections to prevent multiple connections to the same database: ```typescript import { mongoDBConnect } from '@thalorlabs/database'; // First call creates the connection const connection1 = await mongoDBConnect(); // Subsequent calls return the cached connection const connection2 = await mongoDBConnect(); // connection1 === connection2 (same instance) ``` ### Error Handling ```typescript import { mongoDBConnect } from '@thalorlabs/database'; try { const connection = await mongoDBConnect(); console.log('Database connected successfully'); } catch (error) { console.error('Database connection failed:', error); // Handle connection errors } ``` ### Multiple Database Connections ```typescript import mongoose from 'mongoose'; import { MONGO_URI } from '@thalorlabs/database'; // Connect to different databases const primaryConnection = await mongoDBConnect(); const secondaryConnection = await mongoose.createConnection( 'mongodb://localhost:27017/secondary-db' ); ``` ## Type Definitions ### Mongoose Types ```typescript import type { Mongoose } from '@thalorlabs/database'; // Use the Mongoose type for type safety function handleConnection(connection: Mongoose) { // Type-safe connection handling } ``` ### Connection Options ```typescript import type { DEFAULT_CONNECTION_OPTIONS } from '@thalorlabs/database'; // Use the default options type const customOptions = { ...DEFAULT_CONNECTION_OPTIONS, maxPoolSize: 20, }; ``` ## Testing ```bash # Run tests npm test # Run tests with coverage npm run test:coverage # Run tests in watch mode npm run test:watch ``` ## Dependencies - `mongoose`: ^8.18.1 - MongoDB object modeling for Node.js ## Peer Dependencies - `mongoose`: ^8.18.0 ## Best Practices ### 1. Use Environment Variables ```typescript // Good - uses environment configuration const connection = await mongoDBConnect(); // Avoid - hardcoded connection strings const connection = await mongoose.connect('mongodb://localhost:27017/db'); ``` ### 2. Handle Connection Errors ```typescript // Good - proper error handling try { const connection = await mongoDBConnect(); // Use connection } catch (error) { console.error('Connection failed:', error); process.exit(1); } // Avoid - unhandled connection errors const connection = await mongoDBConnect(); // Could throw ``` ### 3. Use Connection Caching ```typescript // Good - leverages connection caching const connection = await mongoDBConnect(); // Cached on subsequent calls // Avoid - creating multiple connections const connection1 = await mongoose.connect(MONGO_URI); const connection2 = await mongoose.connect(MONGO_URI); // Unnecessary ``` ### 4. Configure for Production ```typescript // Good - production-ready configuration const connection = await mongoose.connect(MONGO_URI, { maxPoolSize: 20, serverSelectionTimeoutMS: 10000, socketTimeoutMS: 45000, bufferCommands: false, }); ``` ## Migration Guide ### From Direct Mongoose Usage ```typescript // Before import mongoose from 'mongoose'; const connection = await mongoose.connect( process.env.MONGO_URI || 'mongodb://localhost:27017/db' ); // After import { mongoDBConnect } from '@thalorlabs/database'; const connection = await mongoDBConnect(); ``` ### From Custom Connection Management ```typescript // Before let cachedConnection = null; async function connectToDatabase() { if (cachedConnection) { return cachedConnection; } const connection = await mongoose.connect(MONGO_URI); cachedConnection = connection; return connection; } // After import { mongoDBConnect } from '@thalorlabs/database'; const connection = await mongoDBConnect(); // Handles caching automatically ``` ## Troubleshooting ### Common Issues **Connection Timeout** ```typescript // Increase timeout values const connection = await mongoose.connect(MONGO_URI, { serverSelectionTimeoutMS: 30000, socketTimeoutMS: 60000, }); ``` **Connection Pool Exhausted** ```typescript // Increase pool size const connection = await mongoose.connect(MONGO_URI, { maxPoolSize: 20, minPoolSize: 5, }); ``` **Environment Variable Not Set** ```typescript // Check environment variable console.log('MONGO_URI:', process.env.MONGO_URI); // Provide fallback const mongoUri = process.env.MONGO_URI || 'mongodb://localhost:27017/default-db'; ``` ## License ISC This database utilities package provides a solid foundation for MongoDB connections in TypeScript applications with proper connection management and configuration.