@thalorlabs/database
v1.2.0
Published
Database utilities and connection helpers for TypeScript applications with MongoDB support
Downloads
11
Maintainers
Readme
@thalorlabs/database
A comprehensive database utilities package for TypeScript applications with MongoDB connection management and configuration helpers.
Installation
npm install @thalorlabs/databaseFeatures
- 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
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
import { mongoDBConnect } from '@thalorlabs/database';
// Simple connection
const connection = await mongoDBConnect();With Environment Variables
# Set your MongoDB URI
export MONGO_URI="mongodb://localhost:27017/your-database"import { mongoDBConnect } from '@thalorlabs/database';
// Uses MONGO_URI environment variable
const connection = await mongoDBConnect();Custom Connection Options
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
# Required: MongoDB connection URI
MONGO_URI=mongodb://localhost:27017/your-database
# Optional: Environment
NODE_ENV=productionDefault Configuration
The package provides sensible defaults for MongoDB connections:
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:
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
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
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
import type { Mongoose } from '@thalorlabs/database';
// Use the Mongoose type for type safety
function handleConnection(connection: Mongoose) {
// Type-safe connection handling
}Connection Options
import type { DEFAULT_CONNECTION_OPTIONS } from '@thalorlabs/database';
// Use the default options type
const customOptions = {
...DEFAULT_CONNECTION_OPTIONS,
maxPoolSize: 20,
};Testing
# Run tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode
npm run test:watchDependencies
mongoose: ^8.18.1 - MongoDB object modeling for Node.js
Peer Dependencies
mongoose: ^8.18.0
Best Practices
1. Use Environment Variables
// 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
// 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 throw3. Use Connection Caching
// 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); // Unnecessary4. Configure for Production
// 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
// 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
// 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 automaticallyTroubleshooting
Common Issues
Connection Timeout
// Increase timeout values
const connection = await mongoose.connect(MONGO_URI, {
serverSelectionTimeoutMS: 30000,
socketTimeoutMS: 60000,
});Connection Pool Exhausted
// Increase pool size
const connection = await mongoose.connect(MONGO_URI, {
maxPoolSize: 20,
minPoolSize: 5,
});Environment Variable Not Set
// 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.
