index.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import express, { json, NextFunction, Request, Response, urlencoded } from "express";
  2. import { RegisterRoutes } from "../build/routes";
  3. import { HtmlController } from "./routes/htmlControllers";
  4. import swaggerUi from "swagger-ui-express";
  5. import { engine } from 'express-handlebars';
  6. import path from "path";
  7. import ConfigurationManager from "./config";
  8. import slavery from "./slavery";
  9. import {UnauthorizedMasterApiKey} from "./models/unauthorizedApi";
  10. (async () => {
  11. if (process.argv.indexOf("--generate-key") > 0) {
  12. await slavery.generateKey();
  13. process.exit(0);
  14. }
  15. const app = express();
  16. if (!ConfigurationManager.slave) {
  17. // Whiskers html template
  18. app.engine('handlebars', engine());
  19. app.set('view engine', 'handlebars');
  20. app.set('views', path.join(__dirname, '../templates'));
  21. }
  22. // Swagger UI
  23. app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(require(path.join(__dirname, "../build/swagger.json"))));
  24. // API routes
  25. app.use(
  26. urlencoded({
  27. extended: true,
  28. })
  29. );
  30. app.use(json());
  31. if (!ConfigurationManager.slave)
  32. HtmlController.RegisterHtmlPages(app);
  33. RegisterRoutes(app);
  34. // Error handling
  35. app.use((err: unknown,
  36. _req: Request,
  37. res: Response,
  38. next: NextFunction) => {
  39. if (err instanceof UnauthorizedMasterApiKey) {
  40. return res.status(403).json({
  41. message: "Api key validation failed"
  42. });
  43. }
  44. else if (err instanceof Error) {
  45. return res.status(500).json({
  46. message: err.message
  47. });
  48. }
  49. next();
  50. return;
  51. });
  52. // Static resources
  53. if (!ConfigurationManager.slave) {
  54. app.use("/js/front.js", express.static(path.join(__dirname, "../build/"), {index: 'front.js'}));
  55. app.use("/js/front.min.js", express.static(path.join(__dirname, "../build/"), {index: 'front.min.js'}));
  56. app.use("/js/front.js.map", express.static(path.join(__dirname, "../build/"), {index: 'front.js.map'}));
  57. app.use("/js/front.min.js.map", express.static(path.join(__dirname, "../build/"), {index: 'front.min.js.map'}));
  58. app.use(express.static(path.join(__dirname, 'public')));
  59. }
  60. app.listen(ConfigurationManager.port,
  61. () => console.log(`Server listening on port ${ConfigurationManager.port}.`))
  62. .on("error", (error) => {
  63. throw new Error(error.message);
  64. });
  65. })();