kutt/server/server.js

68 lines
1.8 KiB
JavaScript
Raw Normal View History

2024-08-11 18:41:03 +03:30
const env = require("./env");
const cookieParser = require("cookie-parser");
2024-09-08 14:10:02 +03:30
const passport = require("passport");
2024-08-11 18:41:03 +03:30
const express = require("express");
const helmet = require("helmet");
const morgan = require("morgan");
const path = require("path");
const hbs = require("hbs");
2024-08-21 21:22:59 +03:30
const helpers = require("./handlers/helpers.handler");
2024-09-09 18:43:12 +03:30
const asyncHandler = require("./utils/asyncHandler");
const locals = require("./handlers/locals.handler");
2024-09-08 14:10:02 +03:30
const links = require("./handlers/links.handler");
const { stream } = require("./config/winston");
2024-08-11 18:41:03 +03:30
const routes = require("./routes");
const utils = require("./utils");
2024-09-09 18:43:12 +03:30
require("./cron");
2024-08-11 18:41:03 +03:30
require("./passport");
2024-09-09 18:43:12 +03:30
// create express app
2024-08-11 18:41:03 +03:30
const app = express();
2024-09-12 14:26:39 +03:30
// stating that this app is running behind a proxy
// and the express app should get the IP address from the proxy server
2024-08-11 18:41:03 +03:30
app.set("trust proxy", true);
if (env.isDev) {
app.use(morgan("combined", { stream }));
}
app.use(helmet({ contentSecurityPolicy: false }));
app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static("static"));
2024-09-08 14:10:02 +03:30
app.use(passport.initialize());
2024-09-12 14:26:39 +03:30
app.use(helpers.ip);
2024-09-09 18:43:12 +03:30
app.use(locals.isHTML);
2024-09-12 14:26:39 +03:30
app.use(locals.config);
2024-08-11 18:41:03 +03:30
// template engine / serve html
app.set("view engine", "hbs");
app.set("views", path.join(__dirname, "views"));
2024-08-21 21:22:59 +03:30
utils.registerHandlebarsHelpers();
2024-08-11 18:41:03 +03:30
2024-09-12 14:26:39 +03:30
// render html pages
2024-09-08 14:10:02 +03:30
app.use("/", routes.render);
2024-08-11 18:41:03 +03:30
2024-09-08 14:10:02 +03:30
// if is custom domain, redirect to the set homepage
app.use(asyncHandler(links.redirectCustomDomainHomepage));
2024-08-11 18:41:03 +03:30
2024-09-12 14:26:39 +03:30
// handle api requests
2024-09-08 14:10:02 +03:30
app.use("/api/v2", routes.api);
app.use("/api", routes.api);
2024-08-11 18:41:03 +03:30
2024-09-08 14:10:02 +03:30
// finally, redirect the short link to the target
app.get("/:id", asyncHandler(links.redirect));
2024-08-11 18:41:03 +03:30
2024-09-12 14:26:39 +03:30
// handle errors coming from above routes
2024-08-11 18:41:03 +03:30
app.use(helpers.error);
app.listen(env.PORT, () => {
console.log(`> Ready on http://localhost:${env.PORT}`);
});