-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
67 lines (61 loc) · 1.45 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
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
import express, { Express } from "express";
import cors from "cors";
import router from "./router";
import { connect, ConnectOptions, disconnect } from "mongoose";
import morgan from "morgan";
import { logger, seedData } from "@utils";
import { MONGO_URI, PORT, SEED_DATA } from "@constants";
// Middleware
const createAppWithMiddleware = (): Express => {
const app = express();
app.use(
morgan(
`[:date[web]] :method :url :remote-addr :status :res[content-length] - :response-time ms HTTP/:http-version`,
),
);
app.use(cors());
app.use(express.json());
app.use("/", router);
return app;
};
// Database
const connectToDB = async () => {
try {
await connect(MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
} as ConnectOptions);
} catch (error) {
console.log(error);
}
};
// App
const main = () => {
try {
const app = createAppWithMiddleware();
connectToDB().then(() => {
logger("MongoDb connected");
});
if (SEED_DATA) {
seedData().then(() => {
logger("Event and Merch Data seeded");
});
} else {
logger("Seeding disabled");
}
app.listen(PORT, () => {
logger(`Server started on port ${PORT}`);
});
} catch (error) {
console.log(error);
}
};
main();
const closeApp = () => {
disconnect().then(() => {
logger("MongoDb disconnected");
process.exit();
});
};
process.on("SIGTERM", closeApp);
process.on("SIGINT", closeApp);