title: node.js api keep code dry
body: <p>I was wondering , what is the best practice to keep the code DRY when developing node.js api with database calls.</p>
  
  <p>I seems like I'm having alot of repeated code.</p>
  
  <p>For example, look at this:</p>
  
  <pre><code>app.get('/api/users_count', function (req,res) {
    pool.connect(function(err, client, done) {
      if(err) {
        return console.error('error fetching client from pool', err);
      }
      client.query('SELECT count(*) FROM users;', function(err, result) {
        done();
  
        if(err) {
          return console.error('error running query', err);
        }
        res.json({"users count": result.rows[0].count});
      });
    });
  
  
  });
  </code></pre>
  
  <p>and this:</p>
  
  <pre><code>app.get('/api/users/:id', function (req,res) {
    pool.connect(function(err, client, done) {
      if(err) {
        return console.error('error fetching client from pool', err);
      }
      client.query('SELECT name FROM users WHERE id=$1;',req.param.id, function(err, result) {
  
        done();
  
        if(err) {
          return console.error('error running query', err);
        }
        res.json({"user name": result.rows[0].name});
      });
    });
  
  
  });
  </code></pre>
  
  <p>How can I avoid the repeating of error handing , connect call, and just focus on route and query.</p>
  
  <p>Thanks!</p>