server.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 asyncHandler = require("./utils/asyncHandler");
  11. const locals = require("./handlers/locals.handler");
  12. const links = require("./handlers/links.handler");
  13. const { stream } = require("./config/winston");
  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. if (env.isDev) {
  24. app.use(morgan("combined", { stream }));
  25. }
  26. app.use(helmet({ contentSecurityPolicy: false }));
  27. app.use(cookieParser());
  28. app.use(express.json());
  29. app.use(express.urlencoded({ extended: true }));
  30. app.use(express.static("static"));
  31. app.use(passport.initialize());
  32. app.use(helpers.ip);
  33. app.use(locals.isHTML);
  34. app.use(locals.config);
  35. // template engine / serve html
  36. app.set("view engine", "hbs");
  37. app.set("views", path.join(__dirname, "views"));
  38. utils.registerHandlebarsHelpers();
  39. // render html pages
  40. app.use("/", routes.render);
  41. // if is custom domain, redirect to the set homepage
  42. app.use(asyncHandler(links.redirectCustomDomainHomepage));
  43. // handle api requests
  44. app.use("/api/v2", routes.api);
  45. app.use("/api", routes.api);
  46. // finally, redirect the short link to the target
  47. app.get("/:id", asyncHandler(links.redirect));
  48. // handle errors coming from above routes
  49. app.use(helpers.error);
  50. app.listen(env.PORT, () => {
  51. console.log(`> Ready on http://localhost:${env.PORT}`);
  52. });