webstudio/server/src/core/controllers/app.ts

84 lines
2.2 KiB
TypeScript
Raw Normal View History

2023-10-26 17:44:54 +03:00
import express from "express";
import { Routes } from "../interfaces/router";
import cors from "cors";
import locator from "../di/register_di";
import { DevEnv, UnitTestEnv } from "../di/env";
import mongoose from "mongoose";
2023-11-10 12:06:40 +03:00
import { Server } from "socket.io";
import { createServer } from "http";
import { TypedEvent } from "../helper/typed_event";
import { SocketSubscriber } from "./socket_controller";
2023-10-26 17:44:54 +03:00
export class App {
public app: express.Application;
public port: number;
public env: string;
2023-11-10 12:06:40 +03:00
public socketSubscribers: SocketSubscriber<any>[];
public io: Server;
constructor(routes: Routes[], socketSubscribers: SocketSubscriber<any>[]) {
this.port = 4001;
this.socketSubscribers = socketSubscribers;
2023-10-26 17:44:54 +03:00
this.env = "dev";
2023-11-01 18:24:43 +03:00
this.app = express();
2023-10-27 21:22:48 +03:00
this.loadAppDependencies().then(() => {
this.initializeMiddlewares();
this.initializeRoutes(routes);
});
2023-10-26 17:44:54 +03:00
}
public listen() {
2023-11-10 12:06:40 +03:00
const httpServer = createServer(this.app);
const io = new Server(httpServer, {
cors: { origin: "*" },
});
io.on("connection", (socket) => {
this.socketSubscribers.map((el) => {
el.emitter.on((e) => {
socket.emit(el.event, e);
});
});
});
2023-10-26 17:44:54 +03:00
2023-11-10 12:06:40 +03:00
httpServer.listen(this.port, () => {
2023-10-26 17:44:54 +03:00
console.info(`=================================`);
console.info(`======= ENV: ${this.env} =======`);
console.info(`🚀 HTTP http://localhost:${this.port}`);
console.info(`🚀 WS ws://localhost:${this.port}`);
console.info(`=================================`);
});
2023-11-10 12:06:40 +03:00
this.io = io;
2023-10-26 17:44:54 +03:00
}
public getServer() {
return this.app;
}
private initializeMiddlewares() {
this.app.use(cors());
this.app.use(express.json());
this.app.use(express.urlencoded({ extended: true }));
}
private initializeRoutes(routes: Routes[]) {
routes.forEach((route) => {
this.app.use("/", route.router);
});
}
2023-10-27 21:22:48 +03:00
async loadAppDependencies() {
2023-11-10 12:06:40 +03:00
// await locator(
// this.env == "development"
// ? new DevEnv(this.computedFolder)
// : new UnitTestEnv(this.computedFolder)
// );
2023-10-26 17:44:54 +03:00
mongoose
.connect("mongodb://127.0.0.1:27017/test")
2023-11-10 12:06:40 +03:00
.then(() => {})
2023-10-26 17:44:54 +03:00
.catch((e) => {
console.log("ERROR:", e);
});
}
}