title: How do I design my Node.js API so that I can also consume it from the server side?
body: <p>I have an API that returns some JSON from mongodb:</p>
  
  <pre><code>// In router.js
  var api = require('api') 
  app.get('/lists', api.lists);
  
  // In api.js
  var db = require('db')
  exports.lists = function(req, res) {
    db.lists.find({}, function(err, lists) {
      res.send(lists);
    });
  };
  </code></pre>
  
  <p>Is there a way to design the API so that I could also consume it from within my Node.js app? I'm trying to avoid having to duplicate any of the database code outside the API. I basically have a controller that can render the data server-side:</p>
  
  <pre><code>// In controller.js
  var api = require('api')
  exports.page = function(req, res) {
    res.send(api.lists()); // This won't work
  };
  </code></pre>
  
  <p>I found a hacky solution which was to pass a callback function to the api.lists(), but I have a feeling this is the "wrong" way to achieve this:</p>
  
  <pre><code>// In api.js
  exports.lists = function(req, res, callback) {
    db.lists.find({}, function(err, lists) {
      if(callback){
         callback(lists);
      } else {
         res.send(lists);
      }
    });
  };
  </code></pre>
  
  <p>Any ideas?</p>