server.js 1.9 KB

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