| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- import express, { json, NextFunction, Request, Response, urlencoded } from "express";
- import { RegisterRoutes } from "../build/routes";
- import { HtmlController } from "./routes/htmlControllers";
- import swaggerUi from "swagger-ui-express";
- import { engine } from 'express-handlebars';
- import path from "path";
- import ConfigurationManager from "./config";
- import slavery from "./slavery";
- import {UnauthorizedMasterApiKey} from "./models/unauthorizedApi";
- (async () => {
- if (process.argv.indexOf("--generate-key") > 0) {
- await slavery.generateKey();
- process.exit(0);
- }
- const app = express();
- if (!ConfigurationManager.slave) {
- // Whiskers html template
- app.engine('handlebars', engine());
- app.set('view engine', 'handlebars');
- app.set('views', path.join(__dirname, '../templates'));
- }
- // Swagger UI
- app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(require(path.join(__dirname, "../build/swagger.json"))));
- // API routes
- app.use(
- urlencoded({
- extended: true,
- })
- );
- app.use(json());
- if (!ConfigurationManager.slave)
- HtmlController.RegisterHtmlPages(app);
- RegisterRoutes(app);
- // Error handling
- app.use((err: unknown,
- _req: Request,
- res: Response,
- next: NextFunction) => {
- if (err instanceof UnauthorizedMasterApiKey) {
- return res.status(403).json({
- message: "Api key validation failed"
- });
- }
- else if (err instanceof Error) {
- return res.status(500).json({
- message: err.message
- });
- }
- next();
- return;
- });
- // Static resources
- if (!ConfigurationManager.slave) {
- app.use("/js/front.js", express.static(path.join(__dirname, "../build/"), {index: 'front.js'}));
- app.use("/js/front.min.js", express.static(path.join(__dirname, "../build/"), {index: 'front.min.js'}));
- app.use("/js/front.js.map", express.static(path.join(__dirname, "../build/"), {index: 'front.js.map'}));
- app.use("/js/front.min.js.map", express.static(path.join(__dirname, "../build/"), {index: 'front.min.js.map'}));
- app.use(express.static(path.join(__dirname, 'public')));
- }
- app.listen(ConfigurationManager.port,
- () => console.log(`Server listening on port ${ConfigurationManager.port}.`))
- .on("error", (error) => {
- throw new Error(error.message);
- });
- })();
|