Technique for transferring information between properties of a class instance within an Express server's architecture

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};

Answer №1

If the MonitorServer class has its methods and variables set as public, you can easily access them by using the 'monitor' variable.

Here's an example to illustrate this:

monitor-server.ts

export class MonitorServer extends EventEmitter {
   
   public somePublicFunction() {
      doSomeStuff();
   }
}

auth.ts

let monitor: MonitorServer;
function setMonitorServer(monitorServer: MonitorServer) {
    monitor = monitorServer;
}
router.get('/admin', (req, res) => {
    if (monitor) {
        monitor.somePublicFunction();
    }
})};

Does this explanation address your query? Or were you curious about how to achieve this functionality without needing the setMonitorServer() call in auth.ts?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does the Next.js GET index request keep fetching multiple times instead of just once?

Currently, I am encountering an issue while working on a tutorial app with Next.js. One of my components is not rendering due to what seems like multiple executions of a simple GET request for an index page. The problem perplexes me, and I need some assist ...

Tips on removing either the date or time when input type date and input type time share the same ng-model

In my Ionic app built with AngularJS, I have a form where the date and time are displayed separately but share the same data-ng-model: <input type="date" id ="actualVisitDate" data-ng-model="actualVisitDate" required> <input type="time" id ="actu ...

Is it possible to retrieve the chosen options text from a select menu using jQuery with the feature of "Dynamic option values"?

I need assistance with displaying dynamic drop-down values where only the id values are presently available. What would be the best approach to achieve this? <div class="form-group"> <select class="wp-form-control" id="joblocation" name="jobl ...

dirpagination fails to display all rows in the dataset

I've been working on creating tables with 3 divs, as shown in the link below:- https://github.com/anirbanmishra/congress.php/blob/master/web_test Additionally, I have a javascript file available here:- https://github.com/anirbanmishra/congress.php/bl ...

Cease the use of bi-directional data binding on an Angular directive

One way I've been attempting to send information to a directive is through the following setup: <ui-message data="{{app}}"></ui-message> In my controller, this is how I define it: app.controller("testCtrl", function($scope) { $scope.a ...

Is it possible to continuously update a Google line chart by programmatically adding rows at specific intervals using an AJAX call

Is there a way to dynamically add rows to the Google line chart each time data is retrieved via an AJAX call at set intervals? This is the existing code: google.charts.load('current', {'packages':['line']}); google.charts. ...

Sequelize.Model not being recognized for imported model

I am encountering an issue while trying to implement a sequelize N:M relation through another table. The error message I keep receiving is as follows: throw new Error(${this.name}.belongsToMany called with something that's not a subclass of Sequelize ...

Sluggish Performance of Material UI Table

Hey there! I've been working with Material-UI for a large data table, but I've noticed it's quite slow. Before reaching out on Github, I wanted to see if other users have any tips or workarounds to help improve performance. Here is the code ...

What is the best way to access values from dynamically added components in Svelte when using data from a REST API in a loop?

Previously, I posted this query but now I've made changes to utilize a REST service for retrieving the item list. Everything functions as expected when the data is hardcoded, however, I encounter undefined values when using data from the REST service. ...

What is the reason behind TypeScript requiring me to initialize a property even though I am retrieving its value from a local reference?

I am just beginning to explore Angular. This is the template for my custom component: <div class="row"> <div class="col-xs-12"> <form action=""> <div class="ro"> <d ...

Error message: The 'Access-Control-Allow-Origin' policy is preventing access in a react express docker application

I have successfully set up a front-end React application and a Node/Express API using Docker. The React app is currently running on localhost:3000, while the API is running on localhost:9000. Both applications are fully functional. However, I am encounteri ...

AgGrid's magical dropdown feature

Struggling to integrate a bootstrap-4 dropdown menu with AgGrid, I'm facing an issue where the data table overlaps the dropdown when the html is present. Attempts to increase the z-index have not yielded results. Below is the html code snippet: < ...

Implementing a Typescript hook using useContext along with an uninitialized context object

I am currently attempting to develop a custom hook called useAuth in React 17 with TypeScript. While my solution is somewhat functioning, it requires the following syntax when utilizing the hook methods: const auth = useAuth(); // Do other stuff ...

Is it possible to have a Socket.io session without using express.js?

Looking to establish session management through websockets using node.js and socket.io, without relying on cookies and bypassing express.js. This is important as there may be clients that do not run in a traditional browser environment. Has anyone succes ...

I'm having trouble with my controller - not sure what the problem is

My controller seems to be malfunctioning. I have created a controller but it is not functioning properly. Even though I have reviewed it multiple times, the issue persists. Could someone please assist me with this problem? Angular Code var myPanelSearch ...

Receiving time slots on a bootstrap schedule

I recently developed a calendar using Bootstrap that allows users to select a start date and automatically sets the end date within a 7-day range from the chosen start date. However, I am facing a challenge in enabling users to also pick minutes along with ...

Issue with component not updating upon state change

Having trouble getting my react function component to rerender immediately after updating the state. The application takes input for material cost of each product and calculates the total. I want the component to display the updated total as soon as the i ...

Having trouble interacting with the "Continue" button on PayPal while using Selenium

Recently, I have encountered an issue with automating payments via PayPal Sandbox. Everything used to work smoothly, but now I am unable to click the final Continue button no matter what method I try. I have attempted regular clicks, using the Actions cl ...

Running socket.io and express simultaneously on an elastic beanstalk instance: A step-by-step guide

We are running an Elastic Beanstalk instance with both REST services and Socket.io. Our Express server is configured to start at port 80, while the Socket.io connection is set up on port 3001. Despite turning off the proxy from nginx to disable it, we ar ...

Is it possible that the rows variable is not updating correctly due to an issue with the setState function, resulting in the changes not being displayed in

This code serves a similar purpose to a ToDo List feature. The add button is intended to add an array object to the list of rows, which are displayed in the UI as TextFields through iteration with rows.map. The subtract button should remove the selected ro ...