-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
69 lines (60 loc) · 2.11 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
//* SERVER IMPORT
const express = require("express");
const server = express();
//* ENV IMPORT
const { config } = require("dotenv");
config();
//* OTHER IMPORTS
const path = require("path");
const sessions = require("express-session");
const connectFlash = require("connect-flash");
const csrf = require("csurf");
const { urlencoded } = require("body-parser");
//* SESSION STORE
const mongoDbSessionStore = require("connect-mongodb-session");
const MongoDbStore = mongoDbSessionStore(sessions);
const sessionsStore = new MongoDbStore({
databaseName: process.env.DATABASE_NAME,
collection: "sessions",
uri: process.env.MONGO_URI,
});
const appRoutes = require("./routes/app-routes");
const commonOptionsToViewProvider = require("./middleware/commonOptionsToViewProvider");
const { connectMongoDb } = require("./database/mongo-db");
const authenticatedUserProvider = require("./middleware/authenticatedUserProvider");
const expressGlobalErrorHandlingMiddleware = require("./middleware/expressGlobalErrorHandlingMiddleware");
server.set("view engine", "ejs");
server.set("views", path.join(__dirname, "views"));
server.use(express.static(path.join(__dirname, "public")));
server.use(
sessions({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false,
cookie: {
expires: Date.now() + 86400000,
},
store: sessionsStore,
})
);
//* connectFlash() creates a new cookie in session as soon as the first request hit the server.
server.use(connectFlash());
server.use(urlencoded({ extended: false }), csrf());
server.use(authenticatedUserProvider);
server.use(commonOptionsToViewProvider);
server.use(appRoutes);
server.use(expressGlobalErrorHandlingMiddleware);
const connectMongoDbFailure = () => {
console.log("Unable to connect database.");
};
const connectMongoDbSuccess = () => {
server.listen(process.env.PORT, (err) => {
if (err) {
return console.log(
`Error occurred while starting the port ${process.env.PORT}`
);
}
return console.log(`Server started at port ${process.env.PORT}`);
});
};
connectMongoDb().then(connectMongoDbSuccess).catch(connectMongoDbFailure);