|
| 1 | +// We reuse this import in order to have access to the `body` property in requests |
| 2 | +const express = require("express"); |
| 3 | + |
| 4 | +// ℹ️ Responsible for the messages you see in the terminal as requests are coming in |
| 5 | +// https://www.npmjs.com/package/morgan |
| 6 | +const logger = require("morgan"); |
| 7 | + |
| 8 | +// ℹ️ Needed when we deal with cookies (we will when dealing with authentication) |
| 9 | +// https://www.npmjs.com/package/cookie-parser |
| 10 | +const cookieParser = require("cookie-parser"); |
| 11 | + |
| 12 | +// ℹ️ Serves a custom favicon on each request |
| 13 | +// https://www.npmjs.com/package/serve-favicon |
| 14 | +const favicon = require("serve-favicon"); |
| 15 | + |
| 16 | +// ℹ️ global package used to `normalize` paths amongst different operating systems |
| 17 | +// https://www.npmjs.com/package/path |
| 18 | +const path = require("path"); |
| 19 | + |
| 20 | +// ℹ️ Session middleware for authentication |
| 21 | +// https://www.npmjs.com/package/express-session |
| 22 | +const session = require("express-session"); |
| 23 | + |
| 24 | +// ℹ️ MongoStore in order to save the user session in the database |
| 25 | +// https://www.npmjs.com/package/connect-mongo |
| 26 | +const MongoStore = require("connect-mongo"); |
| 27 | + |
| 28 | +// Connects the mongo uri to maintain the same naming structure |
| 29 | +const MONGO_URI = |
| 30 | + process.env.MONGODB_URI || "mongodb://127.0.0.1:27017/app"; |
| 31 | + |
| 32 | +// Middleware configuration |
| 33 | +module.exports = (app) => { |
| 34 | + // In development environment the app logs |
| 35 | + app.use(logger("dev")); |
| 36 | + |
| 37 | + // To have access to `body` property in the request |
| 38 | + app.use(express.json()); |
| 39 | + app.use(express.urlencoded({ extended: false })); |
| 40 | + app.use(cookieParser()); |
| 41 | + |
| 42 | + // Normalizes the path to the views folder |
| 43 | + app.set("views", path.join(__dirname, "..", "views")); |
| 44 | + // Sets the view engine to handlebars |
| 45 | + app.set("view engine", "hbs"); |
| 46 | + // AHandles access to the public folder |
| 47 | + app.use(express.static(path.join(__dirname, "..", "public"))); |
| 48 | + |
| 49 | + // Handles access to the favicon |
| 50 | + app.use( |
| 51 | + favicon(path.join(__dirname, "..", "public", "images", "favicon.ico")) |
| 52 | + ); |
| 53 | + |
| 54 | + // ℹ️ Middleware that adds a "req.session" information and later to check that you are who you say you are 😅 |
| 55 | + app.use( |
| 56 | + session({ |
| 57 | + secret: process.env.SESSION_SECRET || "super hyper secret key", |
| 58 | + resave: false, |
| 59 | + saveUninitialized: false, |
| 60 | + store: MongoStore.create({ |
| 61 | + mongoUrl: MONGO_URI, |
| 62 | + }), |
| 63 | + }) |
| 64 | + ); |
| 65 | +}; |
0 commit comments