-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
133 lines (108 loc) · 3.41 KB
/
server.ts
File metadata and controls
133 lines (108 loc) · 3.41 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
//Express App Imports
import express, { Express, Request, Response } from "express"
import path from "path"
import http from "http"
import fs from "fs"
import cors from "cors"
import rateLimiter from "express-rate-limit"
import cookieParser from "cookie-parser"
import morgan from "morgan"
import "express-async-errors"
import dotenv from "dotenv"
dotenv.config()
import connectDB from "./utils/db"
//Import Routes
import ApiRoute from "./routes/apiv1"
//Import Middleware
import paginateMW from "./middleware/paginator"
//Import Error Handler
import errorHandler from "./middleware/error-handler"
import socketIo from "./socketio"
import RabbitMQ from './utils/rabbitmq'
//Start Express App
const app: Express = express()
const server: http.Server = http.createServer(app)
//Setting Environment
const PORT: string | number = process.env.PORT || 5000
app.set("trust proxy", 1)
const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(',') ?? []
if (process.env.NODE_ENV === "development")
allowedOrigins.push("https://admin.socket.io" as string)
const corsOptions = {
origin: function (origin: string | undefined, callback: any) {
if (!origin) return callback(null, true)
if (allowedOrigins.indexOf(origin) === -1) {
const msg =
"The CORS policy for this site does not allow access from the specified Origin."
return callback(new Error(msg), false)
}
return callback(null, true)
},
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
optionsSuccessStatus: 204,
credentials: true,
}
//Security Middleware
app.use(
rateLimiter({
windowMs: 15 * 60 * 1000, //15 minutes
max: 5000, //limit each IP to 100 requests per windowMs
}),
)
app.use(cookieParser())
app.use(express.json())
// app.use(helmet()) //set security HTTP headers
app.use(cors(corsOptions)) //enable CORS
//Logger
if (process.env.NODE_ENV === "development") app.use(morgan("dev"))
const logDir: string = path.join(__dirname, "./log")
//create dir if not exist
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir)
}
app.use(
morgan("common", {
stream: fs.createWriteStream(
path.join(__dirname, "./log/httpReqs.log"),
{
flags: "a",
},
),
}),
)
//Functionality Middleware
app.use(paginateMW)
//Routes
app.use("/", express.static("./client/dist"))
app.use("/assets", express.static("./client/dist/assets"))
app.use("/hello", (req: Request, res: Response) => {
res.status(200).json({ message: "Hello World" })
})
app.use("/api/v1", ApiRoute)
//Define Routes Here
app.use("/*", express.static("./client/dist/index.html"))
//Error Handling Middleware
app.use(errorHandler)
// Catch
process.on('unhandledRejection', (reason) => {
console.error('Unhandled Promise Rejection:', reason);
process.exit(1); // Exit with a non-zero status code
});
//Function Start
async function start() {
try {
const db = await connectDB(process.env.MONGO_URL as string)
console.log(`MongoDB Connected: ${db.connection.name}`)
const rabbitMq = await RabbitMQ();
//Socket.io
socketIo(server, rabbitMq, { cors: { origin: allowedOrigins } })
server.listen(PORT, () => {
console.log(
`⚡️[server]: Server is listening on http://localhost:${PORT}`,
)
})
} catch (error) {
console.log(`Error: ${error}`)
}
}
start()