-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
78 lines (62 loc) · 1.75 KB
/
server.js
File metadata and controls
78 lines (62 loc) · 1.75 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
import 'dotenv/config';
import http from 'http';
import app from './src/app.js';
import { connectDB, closeDB } from './src/config/db.js';
const PORT = process.env.PORT || 5000;
const NODE_ENV = process.env.NODE_ENV || 'development';
let server;
const startServer = async() => {
try {
if (!process.env.MONGO_URI) {
throw new Error("MONGO_URI is missing in environment variables");
}
if (!process.env.JWT_SECRET) {
throw new Error("JWT_SECRET is missing in environment variables");
}
await connectDB();
console.log("DB connected successfully");
server = http.createServer(app);
server.listen(PORT, () => {
console.log(`Server running in ${NODE_ENV} mode on port ${PORT}`);
});
} catch(error) {
console.error("Startup error: ", error.message);
process.exit(1);
}
};
startServer();
let isShuttingDown = false;
const shutdownGracefully = (exitCode = 0) => {
if(isShuttingDown) return;
isShuttingDown = true;
if (server) {
server.close(async () => {
await closeDB();
console.log("Server and DB closed gracefully");
process.exit(exitCode);
});
setTimeout(() => {
console.error("Forced shutdown after timeout");
process.exit(exitCode);
}, 10000).unref();
}
else {
process.exit(exitCode);
}
};
process.on("unhandledRejection", (err) => {
console.error("Unhandled Rejection: ", err);
shutdownGracefully(1);
});
process.on("uncaughtException", (err) => {
console.error("Uncaught Exception: ", err);
shutdownGracefully(1);
});
process.on("SIGTERM", () => {
console.log("SIGTERM received. Shutting down...");
shutdownGracefully();
});
process.on("SIGINT", () => {
console.log("SIGINT received. Shutting down...");
shutdownGracefully();
});