1import "dotenv/config";
2import express from "express";
3import cookieParser from "cookie-parser";
4import path from "path";
5
6import config from "./config.js";
7import router from "./routes.js";
8
9import { appSession } from "./session.js";
10const __dirname = import.meta.dirname;
11
12const app = express();
13
14app.use(appSession());
15app.use(cookieParser());
16
17// thanks to wesbos
18// pass variables to our templates + all requests
19app.use((req, res, next) => {
20 res.locals.user = req.session.user || null;
21 res.locals.currentPath = req.path;
22 next();
23});
24
25app.disable("x-powered-by");
26
27// http logger
28app.use((req, res, next) => {
29 res.on("finish", function () {
30 console.log(req.method, decodeURI(req.url), res.statusCode);
31 });
32 next();
33});
34app.use(express.urlencoded({ extended: true }));
35
36app.use(express.static(path.join(__dirname, "public")));
37
38// all application routes
39app.use("/", router);
40
41// 404 and other error handlers
42app.use((req, res, next) => {
43 next({ statusCode: 404, message: "Not found" });
44});
45
46app.use((err, req, res, next) => {
47 let statusCode = err.statusCode || 500;
48 let message = err.message || "Unknown error happened";
49
50 return res.status(statusCode).send(message);
51});
52
53app.listen(config.port, () => {
54 console.log(`[${config.appName}] server listening on port ${config.port}`);
55});