1+ /**
2+ * Express.js Backend for MongoDB Sample MFlix Application
3+ *
4+ * This application demonstrates MongoDB operations using the Node.js driver
5+ * with TypeScript. The code prioritizes readability and educational value
6+ * over performance optimization.
7+ */
8+
9+ import express from 'express' ;
10+ import cors from 'cors' ;
11+ import dotenv from 'dotenv' ;
12+ import { closeDatabaseConnection , connectToDatabase , verifyRequirements } from './config/database' ;
13+ import { errorHandler } from './utils/errorHandler' ;
14+ import moviesRouter from './routes/movies' ;
15+
16+ // Load environment variables from .env file
17+ // This must be called before any other imports that use environment variables
18+ dotenv . config ( ) ;
19+
20+ const app = express ( ) ;
21+ const PORT = process . env . PORT || 3001 ;
22+
23+ /**
24+ * CORS Configuration
25+ * Allows the frontend to communicate with this Express backend
26+ * In production, this should be configured to only allow specific origins
27+ */
28+ app . use ( cors ( {
29+ origin : process . env . CORS_ORIGIN || 'http://localhost:3000' ,
30+ credentials : true
31+ } ) ) ;
32+
33+ /**
34+ * Middleware Configuration
35+ * Express.json() parses incoming JSON requests and puts the parsed data in req.body
36+ * The limit is set to handle potentially large movie documents
37+ */
38+ app . use ( express . json ( { limit : '10mb' } ) ) ;
39+ app . use ( express . urlencoded ( { extended : true , limit : '10mb' } ) ) ;
40+
41+ /**
42+ * API Routes
43+ * All movie-related CRUD operations are handled by the movies router
44+ */
45+ app . use ( '/api/movies' , moviesRouter ) ;
46+
47+ /**
48+ * Root Endpoint
49+ * Provides basic information about the API
50+ */
51+ app . get ( '/' , ( req , res ) => {
52+ res . json ( {
53+ name : 'MongoDB Sample MFlix API' ,
54+ version : '1.0.0' ,
55+ description : 'Express.js backend demonstrating MongoDB operations with the sample_mflix dataset' ,
56+ endpoints : {
57+ movies : '/api/movies'
58+ }
59+ } ) ;
60+ } ) ;
61+
62+ /**
63+ * Global Error Handler
64+ * This middleware catches any unhandled errors and returns a consistent error response
65+ * It should be the last middleware in the chain
66+ */
67+ app . use ( errorHandler ) ;
68+
69+ /**
70+ * Application Startup Function
71+ * Handles database connection, requirement verification, and server startup
72+ */
73+ async function startServer ( ) {
74+ try {
75+ console . log ( 'Starting MongoDB Sample MFlix API...' ) ;
76+
77+ // Connect to MongoDB database
78+ console . log ( 'Connecting to MongoDB...' ) ;
79+ await connectToDatabase ( ) ;
80+ console . log ( 'Connected to MongoDB successfully' ) ;
81+
82+ // Verify that all required indexes and sample data exist
83+ console . log ( 'Verifying requirements (indexes and sample data)...' ) ;
84+ await verifyRequirements ( ) ;
85+ console . log ( 'All requirements verified successfully' ) ;
86+
87+ // Start the Express server
88+ app . listen ( PORT , ( ) => {
89+ console . log ( `Server running on port ${ PORT } ` ) ;
90+ console . log ( `API documentation available at http://localhost:${ PORT } ` ) ;
91+ } ) ;
92+
93+ } catch ( error ) {
94+ console . error ( 'Failed to start server:' , error ) ;
95+
96+ // Exit the process if we can't start properly
97+ // This ensures the application doesn't run in a broken state
98+ process . exit ( 1 ) ;
99+ }
100+ }
101+
102+ /**
103+ * Graceful Shutdown Handler
104+ * Ensures the application shuts down cleanly when terminated
105+ */
106+ process . on ( 'SIGINT' , ( ) => {
107+ console . log ( '\nReceived SIGINT. Shutting down...' ) ;
108+ closeDatabaseConnection ( ) ;
109+ process . exit ( 0 ) ;
110+ } ) ;
111+
112+ process . on ( 'SIGTERM' , ( ) => {
113+ console . log ( '\nReceived SIGTERM. Shutting down...' ) ;
114+ closeDatabaseConnection ( ) ;
115+ process . exit ( 0 ) ;
116+ } ) ;
117+
118+ // Start the server
119+ startServer ( ) ;
0 commit comments