title: es6 classes with express.js, how to pass instance of class so that each route can access?
body: <p>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:</p>
  
  <pre><code>export default class Manager {
    constructor() {
      let self = this;
      self.table = [];
    }
    addEntity(obj){
      let self = this;
      self.table.push(obj);
    }
  }
  </code></pre>
  
  <p>Let's say I run my app and some event happens. I then invoke <code>manager.addEntity(...some_event...);</code>.</p>
  
  <p><code>self.table</code> 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 <code>GET /api/table/</code>. Unfortunately I currently have no way of accessing the instance of the class.</p>
  
  <p>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.</p>
  
  <p>My server is defined using normal recommended code:</p>
  
  <pre><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(() =&gt; {
    server.listen(port, ip, () =&gt; {
      console.log(
        'Express server listening on http://%s:%d, in %s mode',
        ip,
        port,
        env,
      );
    });
  });
  
  export default app;
  </code></pre>