1+ import mongoose from 'mongoose' ;
12import app from './src/app.js' ;
3+ import 'dotenv/config' ;
24
35const PORT = process . env . PORT || 5000 ;
46
5- app . listen ( PORT , ( ) => {
6- console . log ( `Server is running on port ${ PORT } ` ) ;
7- } ) ;
7+ /**
8+ * Connect to MongoDB and start the Express server
9+ */
10+ const startServer = async ( ) => {
11+ try {
12+ // Check if MONGODB_URI is provided
13+ if ( ! process . env . MONGODB_URI ) {
14+ console . error ( '❌ MONGODB_URI is not defined in environment variables' ) ;
15+ process . exit ( 1 ) ;
16+ }
17+
18+ // Connect to MongoDB
19+ console . log ( '🔄 Connecting to MongoDB...' ) ;
20+ await mongoose . connect ( process . env . MONGODB_URI ) ;
21+ console . log ( `✅ Connected to MongoDB: ${ mongoose . connection . name } ` ) ;
22+
23+ // Start Express server
24+ app . listen ( PORT , ( ) => {
25+ console . log ( `🚀 Server is running on port ${ PORT } ` ) ;
26+ console . log ( `📊 Database: ${ mongoose . connection . name } ` ) ;
27+ } ) ;
28+
29+ } catch ( error ) {
30+ console . error ( '❌ Failed to start server:' , error . message ) ;
31+ process . exit ( 1 ) ;
32+ }
33+ } ;
34+
35+ // Handle MongoDB connection events
36+ mongoose . connection . on ( 'error' , ( err ) => {
37+ console . error ( '❌ MongoDB connection error:' , err ) ;
38+ } ) ;
39+
40+ mongoose . connection . on ( 'disconnected' , ( ) => {
41+ console . warn ( '⚠️ MongoDB disconnected' ) ;
42+ } ) ;
43+
44+ // Graceful shutdown
45+ process . on ( 'SIGINT' , async ( ) => {
46+ console . log ( '\n🛑 Shutting down server...' ) ;
47+ await mongoose . connection . close ( ) ;
48+ console . log ( '✅ MongoDB connection closed' ) ;
49+ process . exit ( 0 ) ;
50+ } ) ;
51+
52+ // Start the server
53+ startServer ( ) ;
0 commit comments