methuselah
methuselah

Reputation: 13206

Creating a generic utility method to make database calls

I have two database calls in my NodeJS API that do necessarily the same thing.

app.get(`${BASE_URL}/users`, (req, res) => {
  pool.getConnection((err, connection) => {
    if (err) throw err;
    console.log('Connected as id ' + connection.threadId);
    connection.query('SELECT * from users', (error, results) => {
      connection.release();
      if (error) {
        res.status(400).send('Error in database operation');
      } else {
        res.send(results);
      }
    });
  });
});

app.get(`${BASE_URL}/quizzes`, (req, res) => {
  pool.getConnection((err, connection) => {
    if (err) throw err;
    console.log('Connected as id ' + connection.threadId);
    connection.query('SELECT * from quizzes', (error, results) => {
      connection.release();
      if (error) {
        res.status(400).send('Error in database operation');
      } else {
        res.send(results);
      }
    });
  });
});

What would be the best way of creating a generic method that handles the calls for both? I.e.

function getQuery(query) {
  pool.getConnection((err, connection) => {
    if (err) throw err;
    console.log('Connected as id ' + connection.threadId);
    connection.query(query, (error, results) => {
      connection.release();
      if (error) {
        res.status(400).send('Error in database operation');
      } else {
        res.send(results);
      }
    });
  });
}

then

app.get(`${BASE_URL}/users`, (req, res) => {
  getQuery("SELECT * from quizzes");
});

Upvotes: 0

Views: 436

Answers (1)

mottek
mottek

Reputation: 957

You can use a promise to accomplish this:

function getQuery(query) {
  var promise = new Promise(function(resolve, reject) {
    pool.getConnection((err, connection) => {
      if (err) {
          reject(err);
      } else {
        console.log('Connected as id ' + connection.threadId);
        connection.query(query, (error, results) => {
          connection.release();
          if (error) {
            reject('Error in database operation');
          } else {
            resolve(results);
          }
        });
      }
    });
  });
  return promise;
}

The calls will look like:

app.get(`${BASE_URL}/users`, (req, res) => {
  getQuery('SELECT * from users')
    .then(function(results) {
      res.send(results);
    })
    .catch(function(err) {
      res.status(400).send(err);
    });
});

app.get(`${BASE_URL}/quizzes `, (req, res) => {
  getQuery('SELECT * from quizzes')
    .then(function(results) {
      res.send(results);
    })
    .catch(function(err) {
      res.status(400).send(err);
    });
});

Upvotes: 1

Related Questions