import { AppMasterVars, AppMasterErrors, AppMasterEmitter, AppMasterLogger, AppMasterDB} from "../am-core"; import { AppMasterRouter, AppMasterSockets, AppMasterEndpoint} from "../am-server"; import {createServer} from "http"; import {AppMasterType,AppMasterConfig} from "./types"; import listEndpoints from "express-list-endpoints"; import util from "util"; import dns from "dns"; import {interval,of} from "rxjs"; import {takeWhile,tap,catchError} from "rxjs/operators"; import * as ob from "@onebro/oba-common"; export interface AppMaster extends AppMasterType {} export class AppMaster { get routes():AppMasterEndpoint[]{return listEndpoints(this.app);} async start():Promise{ const {port,host,name,env} = this.vars; await this.db.start(); await this.monitor(); this.server.listen(port,() => { //console.log(this.server.address()); this.events.emit("serverOK",{port,host,name,env}); });} async monitor(){ const check = this.vars.settings.checkConn; const errCtrl = this.e; const events = this.events; if(check){ let live = true; const source = interval(1000 * (ob.bool(check)?10:check)); const loop = source.pipe( takeWhile(() => live), tap(async() => { const isConnected = util.promisify(dns.lookupService); const connected = await isConnected("8.8.8.8",53); ob.ok("Network Connection OK");}), catchError((e:Error) => of((e:Error) => { events.emit("error",errCtrl.map(e)); ob.warn("No Network Connection"); live = false;}))); return loop.subscribe();}} constructor(config:AppMasterConfig) { this.config = config; if(config.events){ this.events = new AppMasterEmitter(config.events); this.events.emit("config",this.config); this.events.on("serverOK",({port,name,env}) => { const serverOK = `${name} is running on port:${port} in ${env} mode`; ob.ok(serverOK);});} if(config.errors) this.e = new AppMasterErrors(config.errors); if(config.vars) this.vars = new AppMasterVars(config.vars); if(config.logger) this.logger = new AppMasterLogger(config.logger); if(config.db) this.db = new AppMasterDB(config.db); if(config.main && config.middleware){ this.app = new AppMasterRouter(config.middleware,config.main,this); this.server = createServer(this.app);} if(config.sockets && this.server) this.io = new AppMasterSockets(config.sockets,this.server); ob.ok("AppMaster configuration done...");}} export default AppMaster;