UNPKG

next-mongo-connector

Version:

A modern, secure MongoDB connector for serverless Next.js apps — built with enterprise-grade security, smart caching, pooling, graceful shutdown handling, and full TypeScript support. Maximum security against hijacking and hacking attempts.

319 lines (313 loc) 10.8 kB
import mongoose from 'mongoose'; /** * Webpack configuration for Next MongoDB Connector * Handles optional dependencies and native modules automatically */ interface NextConfig { webpack?: (config: any, context: any) => any; reactStrictMode?: boolean; poweredByHeader?: boolean; [key: string]: any; } /** * Creates a Next.js configuration with MongoDB-friendly webpack settings */ declare function createNextConfig(customConfig?: NextConfig): NextConfig; /** * Connection options for MongoDB */ interface MongoConnectionOptions { /** Connection options passed to Mongoose */ options?: mongoose.ConnectOptions; /** Database name override */ dbName?: string; /** Enable debug logging */ debug?: boolean; /** Timeout for connection attempts (ms) */ connectionTimeout?: number; /** Maximum number of retry attempts */ maxRetries?: number; /** Delay between retry attempts (ms) */ retryDelay?: number; /** Enable SSL/TLS validation */ validateSSL?: boolean; /** Allowed hosts whitelist for security */ allowedHosts?: string[]; /** Custom connection name for multi-db support */ connectionName?: string; } /** * Connection state enum */ declare enum ConnectionState { DISCONNECTED = "disconnected", CONNECTING = "connecting", CONNECTED = "connected", DISCONNECTING = "disconnecting", ERROR = "error" } /** * Connection metadata */ interface ConnectionInfo { state: ConnectionState; connectedAt?: Date; lastError?: Error; host?: string; database?: string; connectionName: string; retryCount: number; } /** * Security validation result */ interface SecurityValidation { isValid: boolean; errors: string[]; warnings: string[]; } /** * Event callback types */ type OnConnectCallback = (connection: mongoose.Connection, info: ConnectionInfo) => void | Promise<void>; type OnDisconnectCallback = (info: ConnectionInfo) => void | Promise<void>; type OnErrorCallback = (error: Error, info: ConnectionInfo) => void | Promise<void>; /** * Global connection cache interface */ interface CachedConnection { connection: mongoose.Connection; promise: Promise<mongoose.Connection>; info: ConnectionInfo; options: MongoConnectionOptions; onConnect?: OnConnectCallback; onDisconnect?: OnDisconnectCallback; onError?: OnErrorCallback; } /** * Global cache type */ interface GlobalMongoCache { connections: Map<string, CachedConnection>; initialized: boolean; } /** * Extend global object with MongoDB cache */ declare global { var __NEXT_MONGO_CONNECTOR__: GlobalMongoCache | undefined; } /** * Connection pool statistics */ interface PoolStats { totalConnections: number; activeConnections: number; pendingConnections: number; failedConnections: number; connectionNames: string[]; } /** * Health check result */ interface HealthCheck { isHealthy: boolean; connectionName: string; state: ConnectionState; latency?: number; lastPing?: Date; error?: string; } /** * Multi-database connection configuration */ interface MultiDbConnection { uri: string; name: string; options?: MongoConnectionOptions; onConnect?: OnConnectCallback; onDisconnect?: OnDisconnectCallback; onError?: OnErrorCallback; } /** * Connection monitoring options */ interface MonitoringOptions { intervalMs?: number; onHealthChange?: (connectionName: string, isHealthy: boolean) => void; autoReconnect?: boolean; maxReconnectAttempts?: number; } /** * Quick connect options */ interface QuickConnectOptions extends Partial<MongoConnectionOptions> { fallbackUri?: string; skipValidation?: boolean; } /** * Connect to MongoDB with enhanced security and caching * @param uri MongoDB connection URI * @param options Connection options * @param onConnect Callback for successful connection * @param onDisconnect Callback for disconnection * @param onError Callback for connection errors * @returns Promise that resolves to MongoDB connection */ declare function connectMongo(uri?: string, options?: MongoConnectionOptions, onConnect?: OnConnectCallback, onDisconnect?: OnDisconnectCallback, onError?: OnErrorCallback): Promise<mongoose.Connection>; /** * Get database instance from connection * @param connectionName Name of the connection (optional) * @returns Database instance */ declare function getDb(connectionName?: string): mongoose.Connection['db']; /** * Get MongoDB connection instance * @param connectionName Name of the connection (optional) * @returns Connection instance */ declare function getConnection(connectionName?: string): mongoose.Connection; /** * Check if MongoDB is connected * @param connectionName Name of the connection (optional) * @returns True if connected */ declare function isConnected(connectionName?: string): boolean; /** * Check if connected with detailed verification * @param connectionName Name of the connection (optional) * @returns Detailed connection status */ declare function isConnectedWithVerification(connectionName?: string): Promise<{ isConnected: boolean; readyState: number; connectionState: string; details: { readyStateConnected: boolean; infoStateConnected: boolean; connectionExists: boolean; }; }>; /** * Get connection information * @param connectionName Name of the connection (optional) * @returns Connection info */ declare function getConnectionInfo(connectionName?: string): ConnectionInfo | null; /** * Close MongoDB connection * @param connectionName Name of the connection (optional) */ declare function closeConnection(connectionName?: string): Promise<void>; /** * Close all MongoDB connections */ declare function closeAllConnections(): Promise<void>; /** * Get connection pool statistics * @returns Pool statistics */ declare function getPoolStats(): PoolStats; /** * Perform health check on connection * @param connectionName Name of the connection (optional) * @returns Health check result */ declare function healthCheck(connectionName?: string): Promise<HealthCheck>; /** * Validate MongoDB URI for security * @param uri MongoDB URI to validate * @param allowedHosts Optional list of allowed hosts * @returns Validation result */ declare function validateURI(uri: string, allowedHosts?: string[]): SecurityValidation; /** * Validate connection options for security * @param options Connection options to validate * @returns Validation result */ declare function validateOptions(options: mongoose.ConnectOptions): SecurityValidation; /** * Connect to multiple databases simultaneously * @param connections Array of connection configurations * @returns Map of connection names to connection instances */ declare function connectMultiDb(connections: MultiDbConnection[]): Promise<Map<string, mongoose.Connection>>; /** * Get all connection information * @returns Map of connection names to connection info */ declare function getAllConnectionsInfo(): Map<string, ConnectionInfo>; /** * Clean up all connections and resources */ declare function cleanup(): Promise<void>; /** * Reset connector state (useful for testing) */ declare function resetConnectorState(): void; /** * Get MongoDB URI from environment with validation * @param fallbackUri Optional fallback URI * @returns Validated MongoDB URI */ declare function getMongoUri(fallbackUri?: string): string; /** * Quick connect with minimal configuration * @param connectionName Name of the connection * @param options Quick connect options * @returns Promise that resolves to MongoDB connection */ declare function quickConnect(connectionName?: string, options?: QuickConnectOptions): Promise<mongoose.Connection>; /** * Get connection with timeout * @param connectionName Name of the connection * @param timeoutMs Timeout in milliseconds * @returns Promise that resolves to MongoDB connection */ declare function getConnectionWithTimeout(connectionName?: string, timeoutMs?: number): Promise<mongoose.Connection>; /** * Batch health check for all connections * @returns Map of connection names to health check results */ declare function batchHealthCheck(): Promise<Map<string, HealthCheck>>; /** * Wait for connection to be ready (useful for testing) * @param connectionName Name of the connection * @param timeoutMs Timeout in milliseconds * @returns Promise that resolves to MongoDB connection */ declare function waitForConnection(connectionName?: string, timeoutMs?: number): Promise<mongoose.Connection>; /** * Start connection monitoring with automatic reconnection * @param intervalMs Monitoring interval in milliseconds * @param onHealthChange Callback for health changes * @returns Timer ID for stopping monitoring */ declare function startConnectionMonitoring(intervalMs?: number, onHealthChange?: (connectionName: string, isHealthy: boolean) => void): NodeJS.Timeout; declare const _default: { connectMongo: typeof connectMongo; getDb: typeof getDb; getConnection: typeof getConnection; isConnected: typeof isConnected; isConnectedWithVerification: typeof isConnectedWithVerification; getConnectionInfo: typeof getConnectionInfo; closeConnection: typeof closeConnection; closeAllConnections: typeof closeAllConnections; getPoolStats: typeof getPoolStats; healthCheck: typeof healthCheck; validateURI: typeof validateURI; validateOptions: typeof validateOptions; connectMultiDb: typeof connectMultiDb; getAllConnectionsInfo: typeof getAllConnectionsInfo; cleanup: typeof cleanup; resetConnectorState: typeof resetConnectorState; getMongoUri: typeof getMongoUri; quickConnect: typeof quickConnect; getConnectionWithTimeout: typeof getConnectionWithTimeout; batchHealthCheck: typeof batchHealthCheck; waitForConnection: typeof waitForConnection; startConnectionMonitoring: typeof startConnectionMonitoring; ConnectionState: typeof ConnectionState; }; export { type ConnectionInfo, ConnectionState, type HealthCheck, type MongoConnectionOptions, type MonitoringOptions, type MultiDbConnection, type OnConnectCallback, type OnDisconnectCallback, type OnErrorCallback, type PoolStats, type QuickConnectOptions, type SecurityValidation, batchHealthCheck, cleanup, closeAllConnections, closeConnection, connectMongo, connectMultiDb, createNextConfig as createMongoWebpackConfig, createNextConfig, _default as default, getAllConnectionsInfo, getConnection, getConnectionInfo, getConnectionWithTimeout, getDb, getMongoUri, getPoolStats, healthCheck, isConnected, isConnectedWithVerification, quickConnect, resetConnectorState, startConnectionMonitoring, validateOptions, validateURI, waitForConnection };