-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapp.ts
More file actions
178 lines (159 loc) · 4.99 KB
/
app.ts
File metadata and controls
178 lines (159 loc) · 4.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
/**
* Express.js Backend for MongoDB Sample MFlix Application
*
* This application demonstrates MongoDB operations using the Node.js driver
* with TypeScript. The code prioritizes readability and educational value
* over performance optimization.
*/
import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import swaggerUi from "swagger-ui-express";
import {
closeDatabaseConnection,
connectToDatabase,
verifyRequirements,
} from "./config/database";
import { errorHandler } from "./utils/errorHandler";
import moviesRouter from "./routes/movies";
import { swaggerSpec } from "./config/swagger";
import logger from "./utils/logger";
import { requestLogger } from "./middleware/requestLogger";
// Load environment variables from .env file
// This must be called before any other imports that use environment variables
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3001;
/**
* CORS Configuration
* Allows the frontend to communicate with this Express backend
* In production, this should be configured to only allow specific origins
*/
app.use(
cors({
origin: process.env.CORS_ORIGIN || "http://localhost:3000",
credentials: true,
})
);
/**
* Middleware Configuration
* Express.json() parses incoming JSON requests and puts the parsed data in req.body
* The limit is set to handle potentially large movie documents
*/
app.use(express.json({ limit: "10mb" }));
app.use(express.urlencoded({ extended: true, limit: "10mb" }));
/**
* Request Logging Middleware
* Logs all incoming HTTP requests with method, URL, status code, and response time
*/
app.use(requestLogger);
/**
* Swagger API Documentation
* Provides interactive API documentation at /api-docs
*/
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerSpec));
/**
* API Routes
* All movie-related CRUD operations are handled by the movies router
*/
app.use("/api/movies", moviesRouter);
/**
* Root Endpoint
* Provides basic information about the API
* @swagger
* /:
* get:
* summary: Get API information
* description: Returns basic information about the API and available endpoints
* tags: [Info]
* responses:
* 200:
* description: API information
* content:
* application/json:
* schema:
* type: object
* properties:
* name:
* type: string
* example: MongoDB Sample MFlix API
* version:
* type: string
* example: 1.0.0
* description:
* type: string
* endpoints:
* type: object
* properties:
* movies:
* type: string
* example: /api/movies
* documentation:
* type: string
* example: /api-docs
*/
app.get("/", (req, res) => {
res.json({
name: "MongoDB Sample MFlix API",
version: "1.0.0",
description:
"Express.js backend demonstrating MongoDB operations with the sample_mflix dataset",
endpoints: {
movies: "/api/movies",
documentation: "/api-docs",
},
});
});
/**
* Global Error Handler
* This middleware catches any unhandled errors and returns a consistent error response
* It should be the last middleware in the chain
*/
app.use(errorHandler);
/**
* Application Startup Function
* Handles database connection, requirement verification, and server startup
*/
async function startServer() {
try {
logger.info("Starting MongoDB Sample MFlix API...");
// Connect to MongoDB database
logger.info("Connecting to MongoDB...");
await connectToDatabase();
logger.info("Connected to MongoDB successfully");
// Verify that all required indexes and sample data exist
logger.info("Verifying requirements (indexes and sample data)...");
await verifyRequirements();
logger.info("All requirements verified successfully");
// Start the Express server
app.listen(PORT, () => {
logger.info(`Server running on port ${PORT}`);
logger.info(`API documentation available at http://localhost:${PORT}/api-docs`);
});
} catch (error) {
logger.error("Failed to start server:", error);
// Exit the process if we can't start properly
// This ensures the application doesn't run in a broken state
process.exit(1);
}
}
/**
* Graceful Shutdown Handler
* Ensures the application shuts down cleanly when terminated
*/
process.on("SIGINT", () => {
logger.info("Received SIGINT. Shutting down gracefully...");
closeDatabaseConnection();
process.exit(0);
});
process.on("SIGTERM", () => {
logger.info("Received SIGTERM. Shutting down gracefully...");
closeDatabaseConnection();
process.exit(0);
});
// Export the app for testing
export { app };
// Only start the server if this file is run directly (not imported for testing)
if (require.main === module) {
startServer();
}