UNPKG

@scefira/dfw-nodejs

Version:
115 lines (96 loc) 3.17 kB
import { DFWConfig, DFWScheme } from "../.."; import DatabaseManager, { Database } from "../modules/DatabaseManager"; import SessionManager from "../modules/SessionManager"; import APIManager from "../modules/APIManager"; import SecurityManager from "../modules/SecurityManager"; import _ from "lodash"; import cookieParser = require("cookie-parser"); import { AddressInfo } from "net"; import { Express, Response, Request} from "express"; export default class DFWInstance { /** * default DFW config */ public config: DFWConfig = { databases: { default: { username: "root", password: "", database: "dfw", host: "localhost", dialect: "mysql", logging: false } } }; /** * */ public modules = { "DatabaseManager" : new DatabaseManager(), "SessionManager" : new SessionManager(), "APIManager" : new APIManager(), "SecurityManager" : new SecurityManager(), } /** * */ public server: Express; /** * Initialices all dependencies and middlewares for DFW */ public constructor(config?: DFWConfig) { this.config = _.merge({}, this.config, config); // combine config object Object.keys(this.modules).forEach(key => { if (this.modules[key].initialice(this)) { console.log(`[DFW] Module ${key} initialiced`); } }) console.log("[DFW] Core loaded mode: " + process.env.NODE_ENV); } /** * Initialices the express server * @param port * @param callback */ public startServer(port: number = process.env.NODE_ENV !== 'production' ? parseInt(process.env.PORT || '3000', 10) : 80, callback?: Function): Express { if (this.server === undefined) { this.server = require("express")(); this.server.use(cookieParser()); let listener = this.server.listen(port, () => { console.log("[DFW] Express server running on port " + (listener.address() as AddressInfo).port); if (callback != undefined && callback != null) { callback(); } }); } return this.server; } /** * * @param req * @param res */ public async touchAsync(req: Request, res: Response) { let dfw: DFWScheme = { session: { isLogged: false, model: {} as any }, request: req, response: res, } var moduleKeys = Object.keys(this.modules); for (var i = 0; i < moduleKeys.length; i++) { await this.modules[moduleKeys[i]].touchAsync(dfw) } return dfw; } /** * * @param name */ public getDatabase(name: string = "default"): Database { return this.modules.DatabaseManager.getDatabase(name); } }