forked from inrittik/BlogPost
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.ts
42 lines (37 loc) · 1.03 KB
/
server.ts
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
import { httpServer } from "./app";
import mongoose from "mongoose";
import dotenv from "dotenv";
import path from "path";
dotenv.config({ path: path.join(__dirname, `./.env`) });
let server: any;
mongoose.connect(<string>process.env.MONGODB_URI).then(() => {
console.log(`⚡️[DB]: Connected`);
server = httpServer.listen(process.env.PORT, () => {
console.log(`⚡️[Server]: Listening on port ${process.env.PORT}`);
});
});
const exitHandler = () => {
if (server) {
server.close(() => {
console.log("Server closed");
process.exit(1);
});
} else {
process.exit(1);
}
};
const unexpectedErrorHandler = (error: unknown) => {
let message: string;
if (error instanceof Error) message = error.message;
else message = String(error);
console.log(message);
exitHandler();
};
process.on("uncaughtException", unexpectedErrorHandler);
process.on("unhandledRejection", unexpectedErrorHandler);
process.on("SIGTERM", () => {
console.log("SIGTERM received");
if (server) {
server.close();
}
});