title: Best Way to Use OOP in Express REST API?
body: <p>I'm going all in and doing a project using only node. It's been a lot of fun, but sometimes I get a little lost in it and I want to try to gain understanding as I get confused so I build it correctly and don't get too overwhelmed. Anyway, here's the problem: </p>
  
  <p>I have REST API that's using Express and mysql. I set up mysql:</p>
  
  <h2>app.js</h2>
  
  <pre><code>//Variables, move these to env
  var dbOptions = {
      host: config.db_config.host,
      user: config.db_config.user,
      password: config.db_config.password,
      port: config.db_config.port,
      database: config.db_config.database
  };
  app.use(myConnection(mysql, dbOptions, 'single'));
  </code></pre>
  
  <p>and then I include my routes, passing the routes the app and log middleware so I can use them in the route:</p>
  
  <h2>app.js cont.</h2>
  
  <pre><code>var userRoute = require('./routes/users.js')(app,log);
  app.use('/users', userRoute);
  </code></pre>
  
  <p>That actually was a little confusing, but now I get it, I have to pass them into module in order for the module to get the data.</p>
  
  <p>Then in my route file I want to use an object so that I can use the same functionality in other routes, but in the user file in order to use the same connection pool that everything else is using, or at least to not have to set up the connection again I have to pass it the response and request? There's gotta be a better way to do that. It's really ugly that way. Here's the relevant part of </p>
  
  <h2>routes/users.js</h2>
  
  <pre><code>var User = require('../controllers/User.js');
  
  module.exports = (function(app,log) {
  var userR = express.Router();
  
  userR.post('/register', function(req,res){
          var email = req.body.email;
          var password = req.body.password;
          var firstName = req.body.first_name;
          var lastName = req.body.last_name;
          var userId;
  
          try {
              var query;
              var status = 200;
              var response = '';
  
              var newUser = {
                  email: email,
                  password:password,
                  first_name: firstName,
                  last_name: lastName,
                  password: password
              };
  
              var user = new User(req,res);
  
              user.register(newUser);
  ...
  
  };
  </code></pre>
  
  <h2>controllers/User.js</h2>
  
  <pre><code>module.exports = function User(req,res) {
  this.id = 0;
      this.register = function(newUser){
  
          var _this = this;
          var deferred = q.defer();
  req.getConnection(function(err,connection){
  ...
  </code></pre>
  
  <p>There must be a pattern I'm missing here. I should just be able to pass the app or something and have access to the req.getConnection etc.</p>
  
  <p>Thanks.</p>