server.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const env = require("./env");
  2. const cookieParser = require("cookie-parser");
  3. const passport = require("passport");
  4. const express = require("express");
  5. const helmet = require("helmet");
  6. const morgan = require("morgan");
  7. const path = require("path");
  8. const hbs = require("hbs");
  9. const helpers = require("./handlers/helpers.handler");
  10. const renders = require("./handlers/renders.handler");
  11. const asyncHandler = require("./utils/asyncHandler");
  12. const locals = require("./handlers/locals.handler");
  13. const links = require("./handlers/links.handler");
  14. const routes = require("./routes");
  15. const utils = require("./utils");
  16. require("./cron");
  17. require("./passport");
  18. // create express app
  19. const app = express();
  20. // stating that this app is running behind a proxy
  21. // and the express app should get the IP address from the proxy server
  22. app.set("trust proxy", true);
  23. app.use(helmet({ contentSecurityPolicy: false }));
  24. app.use(cookieParser());
  25. app.use(express.json());
  26. app.use(express.urlencoded({ extended: true }));
  27. app.use(express.static("static"));
  28. app.use(passport.initialize());
  29. app.use(helpers.ip);
  30. app.use(locals.isHTML);
  31. app.use(locals.config);
  32. // template engine / serve html
  33. app.set("view engine", "hbs");
  34. app.set("views", path.join(__dirname, "views"));
  35. utils.registerHandlebarsHelpers();
  36. // render html pages
  37. app.use("/", routes.render);
  38. // if is custom domain, redirect to the set homepage
  39. app.use(asyncHandler(links.redirectCustomDomainHomepage));
  40. // handle api requests
  41. app.use("/api/v2", routes.api);
  42. app.use("/api", routes.api);
  43. // finally, redirect the short link to the target
  44. app.get("/:id", asyncHandler(links.redirect));
  45. // 404 pages that don't exist
  46. app.get("*", renders.notFound);
  47. // handle errors coming from above routes
  48. app.use(helpers.error);
  49. app.listen(env.PORT, () => {
  50. console.log(`> Ready on http://localhost:${env.PORT}`);
  51. });