MangoRecipe/Source/Webserver/index.ts

57 lines
1.7 KiB
TypeScript

import express from "express";
import { Liquid } from "liquidjs";
import path from "path";
// import { apiRoutes } from "./routes/api";
// import { authRoutes } from "./routes/auth";
import { indexRoutes } from "./routes/index";
const isProduction = process.env.NODE_ENV === "production";
const LAYOUTS_DIRECTORY = path.join(__dirname, "layouts");
const PARTIALS_DIRECTORY = path.join(__dirname, "partials");
const PUBLIC_DIRECTORY = path.join(__dirname, "public");
const VIEWS_DIRECTORY = path.join(__dirname, "views");
export function startWebserver(config: any) {
const app = express();
app.disable("x-powered-by");
app.use(express.urlencoded({ extended: true, limit: "1mb" }));
app.use(express.json({ limit: "1mb" }));
// Liquid engine options
const engine = new Liquid({
root: [VIEWS_DIRECTORY, PARTIALS_DIRECTORY, LAYOUTS_DIRECTORY],
cache: isProduction,
lenientIf: true,
jsTruthy: true,
extname: ".liquid",
});
if (config) {
console.log(config.port);
}
// View engine options
app.engine("liquid", engine.express());
app.set("views", [VIEWS_DIRECTORY, PARTIALS_DIRECTORY, LAYOUTS_DIRECTORY]);
app.set("view engine", "liquid");
// Uses public folder
app.use("/public/", express.static(PUBLIC_DIRECTORY));
// Routes
app.use("/", indexRoutes());
// 404 handler
app.use((req, res) => {
if (req.accepts("html")) return res.status(404).render("404", { url: req.url, errorCode: 404 });
else if (req.accepts("json")) return res.status(404).send({ error: "404" });
else res.status(404).type("txt").send("404");
});
app.listen(config.port, "0.0.0.0", () => {
console.log(`Webserver running on port ${config.port}`);
});
}