-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
151 lines (128 loc) · 4.17 KB
/
app.js
File metadata and controls
151 lines (128 loc) · 4.17 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
const mongoose = require("mongoose");
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const http = require("http");
const cors = require("cors");
// Load environment variables
require('dotenv').config();
// Import utilities and middleware
const logger = require("./utils/logger");
const { generalLimiter } = require("./middleware/rate-limiter");
const { initializeSocket } = require("./config/socket");
// Import routes
const authRoutes = require("./routes/auth");
const userRoutes = require("./routes/users");
const petRoutes = require("./routes/pets");
const reportRoutes = require("./routes/reports");
// Import controllers for Socket.io integration
const reportController = require("./controllers/reportController");
const app = express();
const server = http.createServer(app);
const MONGODB_URI = `mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASSWORD}@missingpet.mrdfzgj.mongodb.net/${process.env.DEFAULT_DATABASE}?authSource=admin&retryWrites=true&w=majority`;
// Middleware
app.use(cors({
origin: process.env.CLIENT_URL || "*",
credentials: true
}));
app.use(bodyParser.urlencoded({ extended: true })); // x-www-form-urlencoded <form>
app.use(bodyParser.json()); // application/json
// Rate limiting
app.use(generalLimiter);
// Static files
app.use("/attachments", express.static(path.join(__dirname, "attachments")));
app.use("/docs", express.static(path.join(__dirname, "docs")));
// Logging middleware
app.use((req, res, next) => {
logger.info(`${req.method} ${req.path} - ${req.ip}`);
next();
});
// CORS headers
app.use((req, res, next) => {
res.setHeader(
"Access-Control-Allow-Methods",
"OPTIONS, GET, POST, PUT, PATCH, DELETE"
);
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
// Routes
app.use("/auth", authRoutes);
app.use("/users", userRoutes);
app.use("/pets", petRoutes);
app.use("/reports", reportRoutes);
// Health check endpoint
app.get("/health", (req, res) => {
res.status(200).json({
status: "OK",
timestamp: new Date().toISOString(),
uptime: process.uptime()
});
});
// 404 handler
app.use((req, res, next) => {
const error = new Error(`Route ${req.originalUrl} not found`);
error.statusCode = 404;
next(error);
});
// Error handling middleware
app.use((error, req, res, next) => {
const status = error.statusCode || 500;
const message = error.message || "Internal server error";
const data = error.data;
logger.error(`Error ${status}: ${message}`, {
error: error.stack,
url: req.url,
method: req.method,
ip: req.ip
});
res.status(status).json({
status,
message,
data,
...(process.env.NODE_ENV === 'development' && { stack: error.stack })
});
});
// Initialize Socket.io
const io = initializeSocket(server);
reportController.setSocketIO(io);
mongoose.connect(MONGODB_URI, {
// Modern connection options
})
.then(() => {
logger.info("Connected to MongoDB");
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '0.0.0.0'; // Bind to all interfaces for development
server.listen(PORT, HOST, () => {
logger.info(`Server is running on port ${PORT} (host: ${HOST})`);
console.log(`Server is running on port ${PORT} (host: ${HOST})`);
console.log(`Health check available at: http://localhost:${PORT}/health`);
console.log(`Network access available at: http://192.168.2.27:${PORT}/health`);
});
})
.catch((error) => {
logger.error("MongoDB connection error:", error);
console.error("MongoDB connection error:", error);
process.exit(1);
});
// Graceful shutdown
process.on('SIGTERM', () => {
logger.info('SIGTERM received, shutting down gracefully');
server.close(() => {
logger.info('Server closed');
mongoose.connection.close(false, () => {
logger.info('MongoDB connection closed');
process.exit(0);
});
});
});
process.on('SIGINT', () => {
logger.info('SIGINT received, shutting down gracefully');
server.close(() => {
logger.info('Server closed');
mongoose.connection.close(false, () => {
logger.info('MongoDB connection closed');
process.exit(0);
});
});
});