I have a class class defined to keep track of some dynamic data that will be updated during runtime. I want the instance of this class to be accessible by all routes I have defined in my application:
export default class Manager {
constructor() {
let self = this;
self.table = [];
}
addEntity(obj){
let self = this;
self.table.push(obj);
}
}
Let's say I run my app and some event happens. I then invoke manager.addEntity(...some_event...);
.
self.table
will then have a new element. I want to be able to have a route access this information by requesting the route's url, maybe GET /api/table/
. Unfortunately I currently have no way of accessing the instance of the class.
Should I assign the reference to the instance of the class to a global variable? This is an anti-pattern and I'd like to avoid doing this if possible.
My server is defined using normal recommended code:
import http from 'http';
import { env, mongo, port, ip, apiRoot } from './config';
import api from './api';
import express from './services/express';
import mongoose from './services/mongoose';
import Manager from './lib/manager.js';
const app = express(apiRoot, api);
const server = http.createServer(app);
mongoose.connect(mongo.uri, { useMongoClient: true });
mongoose.Promise = Promise;
new Manager().initialize(server);
setImmediate(() => {
server.listen(port, ip, () => {
console.log(
'Express server listening on http://%s:%d, in %s mode',
ip,
port,
env,
);
});
});
export default app;