-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
73 lines (58 loc) · 1.62 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
"use strict";
require("dotenv").config();
const bodyParser = require("body-parser");
const express = require("express");
const session = require("express-session");
const mongoose = require("mongoose");
// Init application
const app = express();
// Database
mongoose.Promise = global.Promise; // Override deprecated property
mongoose.connect(process.env.DATABASE, {
useMongoClient: true // Override deprecated property
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
// Sessions
const MongoStore = require("connect-mongo")(session);
app.use(session({
secret: process.env.SESSION_SECRET || "kJAh9pp6Z5n07yT",
resave: true,
saveUninitialized: false,
store: new MongoStore({
mongooseConnection: db
})
}));
app.use((req, res, next) => {
res.locals.userId = req.session.userId;
next();
});
// View templating
app.set("view engine", "ejs");
app.set("views", `${__dirname}/views`);
// Static file directory
app.use(express.static(`${__dirname}/public`));
// Request parser
const jsonParser = bodyParser.json();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(jsonParser);
app.use(urlencodedParser);
// Request router
const routes = require("./routes/routes");
app.use("/", routes);
// Errors
app.use((req, res, next) => {
const err = new Error("File not found.");
err.status = 404;
next(err);
});
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.render("error", {
message: err.message
});
});
// Request listener
app.listen(process.env.PORT || 4000, () => {
console.log("App listening for requests");
});