I am in the process of developing a monitoring server for a library using Express. My goal is to create different routers and routes, while also being able to access functions and variables from the monitor-server class. Currently, I have passed the 'this' variable to the different routes. However, I am wondering if there is a more efficient solution or architecture that I should consider for constructing the routers and initializing them. It is important that the express server is represented as a class.
monitor-server.ts
import * as express from 'express'
import * as path from 'path';
import * as cookieParser from 'cookie-parser';
import * as logger from 'morgan';
import * as cors from 'cors';
import * as useragent from 'express-useragent';
import * as http from 'http';
import * as process from 'process';
import {EventEmitter} from "events";
const authRouter = require('./routes/auth');
export class MonitorServer extends EventEmitter {
public app: express.Application;
private server: http.Server ;
private port = 3000;
private type: 0 | 1 = 1;
private dBMode: 0 | 1 | 2 = 0;
private admin ?: {
username: string;
password: string;
};
constructor() {
super();
this.app = express();
this.app.set('port', this.port);
this.app.set('type', this.type);
this.initializeMiddlewares();
this.initializeControllers();
this.listen();
}
private initializeMiddlewares() {
// initialize middlewares
}
private initializeControllers() {
this.app.use('/auth', authRouter.router);
authRouter.setMonitorServer(this);
}
public listen() {
this.server = http.createServer(this.app);
this.server.listen(this.port);
}
}
auth.ts
import * as express from "express";
import {MonitorServer} from "../monitor-server";
let router = express.Router();
let monitor: MonitorServer;
function setMonitorServer(monitorServer: MonitorServer) {
monitor = monitorServer;
}
router.get('/admin', (req, res) => {
// accessing variables and data within monitor-server class
});
router.get('/operationMode', (req, res) => {
// accessing variables and data within monitor-server class
});
module.exports = {router, setMonitorServer};