-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
63 lines (50 loc) · 1.58 KB
/
server.js
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
/**
* @file server.js
* @description Server configuration and initialization.
*/
// Load environment variables from .env file
require("dotenv").config();
// Load required modules
const express = require("express");
const bodyParser = require("body-parser");
const preprocessRequestDetailsMiddleware = require("./src/middlewares/preprocessRequestDetailsMiddleware");
const responseMiddleware = require("./src/middlewares/responseMiddleware");
const authMiddleware = require("./src/middlewares/authMiddleware");
const db = require("./src/db/db");
const routes = require("./src/routes");
const port = process.env.PORT || 5000;
const host = process.env.HOST || "localhost";
const app = express();
// Trust the first proxy
app.set("trust proxy", 1);
// Connect to the database
if (process.env.NODE_ENV !== "test") db.connectDB();
// Middleware setup
app.use(bodyParser.json());
app.use(preprocessRequestDetailsMiddleware);
app.use(responseMiddleware);
app.use(authMiddleware);
// Routes setup
app.use("/api", routes);
// Start the server
const server = app.listen(port, host, () => {
console.log(`Server running at http://${host}:${port}/`);
});
// Handle SIGTERM gracefully
process.on("SIGTERM", async () => {
console.info("SIGTERM signal received.");
console.log("Closing server...");
await app.close();
});
// Handle SIGINT gracefully
process.on("SIGINT", async () => {
console.info("SIGINT signal received.");
console.log("Closing server...");
await app.close();
});
app.close = async () => {
await db.disconnectDB();
server.close();
};
// Export the app for testing
module.exports = app;