import express, {Application} from "express" import path from "path" import cookieParser from "cookie-parser" import bodyParser from "body-parser" import { ParseToken } from "../middleware/ParseToken" import cors from "cors" import {Router} from "./RouteServiceProvider"; import {IMiddlewareCollection} from "../middleware/IMiddleware"; import {IController} from "../controllers/IController"; import fs from "fs" export class AppServiceProvider { #app: Application; #port: string; #router: Router; #baseDir: string; #controllers: IController[] = []; static #instance: AppServiceProvider; constructor() { this.#app = express(); this.#app.use(cors()); this.#app.use(cookieParser()); this.#app.use(bodyParser.json()); this.#app.use(bodyParser.urlencoded({ extended: false })); this.#app.use(ParseToken); this.#app.set("view engine", "ejs"); this.#app.set("views", path.join(__dirname, "..", "views")) this.#router = Router.create(); } public async loadControllers() { const normalizedPath = path.join(this.getBaseDir(), "controllers"); for (const file of fs.readdirSync(normalizedPath)) { const importedFile = await import(this.getBaseDir() + "/controllers/" + file); const controller: IController = new importedFile.default() as IController; this.#controllers.push(controller) } } public static getControllers() { return this.getInstance().#controllers; } public static create() { this.#instance = new this(); return this.#instance; } public static getInstance() { return this.#instance } public setBaseDir(dir) { this.#baseDir = dir; } public getBaseDir() { return this.#baseDir; } public setPort(port) { this.#port = port; } public getRouter() { return this.#router; } public registerMiddlewares(middlewareCollection: IMiddlewareCollection) { this.#router.setMiddlewares(middlewareCollection); } public async loadRoutes() { await import(this.getBaseDir()+"/routes") } public async setup(cb) { await cb(); } public async listen() { console.log(this.#controllers) this.#app.use(this.#router.getRouter()); console.log(this.#router.routes) this.#router.run() return this.#app.listen(this.#port, () => { console.log(`App started on port ${this.#port}`); }) } }