-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
149 lines (132 loc) · 3.8 KB
/
app.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
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
const createError = require("http-errors");
const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");
const logger = require("morgan");
const cors = require("cors");
const mongoose = require("mongoose");
const passport = require("passport");
const session = require("express-session");
const MongoStore = require("connect-mongo")(session);
const compression = require("compression");
const User = require("./models/User");
require("dotenv").config();
// MONGODB
const forceProdDB = false;
const isProdDb =
forceProdDB ||
(process.env.NODE_ENV === "production" && process.env.REACT_APP_DB_PROD);
const URI = isProdDb
? process.env.REACT_APP_DB_PROD
: process.env.REACT_APP_DB_DEV;
mongoose.connect(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
auto_reconnect: true,
reconnectTries: Number.MAX_SAFE_INTEGER,
reconnectInterval: 1000,
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "*** DB connection error ***"));
db.on("disconnected", console.error.bind(console, "*** DB disconnected ***"));
db.on("reconnected", console.error.bind(console, "*** DB reconnected ***"));
db.once("open", () => {
console.log("db connection:", isProdDb ? "prod" : "dev");
});
// PORT
const PORT = process.env.PORT || 8081;
const app = express();
const server = app.listen(PORT, () => {
console.log(`listening at ${PORT}`);
});
// MIDDLEWARE
const corsCfg = {
origin: "*",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
preflightContinue: false,
optionsSuccessStatus: 204,
credentials: true,
};
app.use(cors(corsCfg));
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
if (process.env.NODE_ENV === "production") {
app.use(compression());
}
// PASSPORT
app.use(
session({
secret: process.env.REACT_APP_SESSION_SECRET,
resave: false,
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
})
);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser((user, done) => {
done(null, user._id);
});
passport.deserializeUser((id, done) => {
// find user based on id stored in cookie
// save user data to req.user
User.findById(id)
.populate("bm.listings")
.populate("chatrooms")
.then((user) => {
done(null, user);
})
.catch((e) => {
done(new Error("Failed to deserialize a user"));
});
});
// ROUTING
app.use("/api", require("./routes"));
// SOCKET IO
require("./socket").listen(server);
// VIEW ENGINE
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
// FORCE HTTPS ON PROD
// eslint-disable-next-line consistent-return
app.use((req, res, next) => {
if (
!req.secure &&
req.get("x-forwarded-proto") !== "https" &&
process.env.NODE_ENV === "production"
) {
return res.redirect(`https://${req.get("host")}${req.url}`);
}
next();
});
// PROD SERVE FRONTEND
if (process.env.NODE_ENV === "production") {
const HALF_HOUR = 1000 * 60 * 30;
app.use(express.static(path.join(__dirname)));
app.use(
express.static(path.join(__dirname, "client", "build"), {
maxAge: HALF_HOUR,
})
);
app.get("/*", (req, res) => {
res.sendFile(path.join(__dirname, "client", "build", "index.html"));
});
} else {
app.use(express.static(path.join(__dirname, "public")));
}
// catch 404 and forward to error handler
app.use((req, res, next) => {
next(createError(404));
});
// error handler
app.use((err, req, res) => {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
// render the error page
res.status(err.status || 500);
res.render("error");
});
module.exports = app;