-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
68 lines (55 loc) · 1.57 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
64
65
66
67
68
import express from "express";
import dotenv from "dotenv";
import mongoose from "mongoose";
import authRoute from "./routes/auth.js";
import usersRoute from "./routes/users.js";
import hotelsRoute from "./routes/hotels.js";
import roomsRoute from "./routes/rooms.js";
import cookieParser from "cookie-parser";
import cors from "cors";
import helmet from "helmet";
const app = express();
dotenv.config();
const PORT = process.env.PORT || 4000
const connect = async () => {
try {
await mongoose.connect(process.env.MONGO);
console.log("Connected to MongoDB")
} catch (error) {
throw error;
}
}
// if there is a connection problem
mongoose.connection.on("disconnected", () => {
console.log("Disconnected from MongoDB")
})
// IMPORT SECURITY
let corsOption = {
origin: "http://localhost:3000",
method: "GET, POST, DELETE, PUT, PATCH"
}
app.use(helmet());
app.use(cors(corsOption))
// middlewares
app.use(cookieParser())
// this enables express receive json objects
app.use(express.json())
app.use("/api/auth", authRoute)
app.use("/api/users", usersRoute)
app.use("/api/hotels", hotelsRoute)
app.use("/api/rooms", roomsRoute)
// handling errors in express server
app.use((err, req, res, next) => {
const errorStatus = err.status || 500
const errorMessage = err.message || "Sorry, there is a problem with our server."
return res.status(errorStatus).json({
success: false,
status: errorStatus,
message: errorMessage,
stack: err.stack
})
})
app.listen(PORT, () => {
connect()
console.log(`App is running at port ${PORT}`)
})