0

I am writing a small application and which communicates with the DB, instead of using callback pattern I am using Promises to simplify my code. Having done a fair amount of coding I can now see some pattern very frequently in my code, I need to know how can I refactor it so that the similar logic is at a single place.

  var queryString = "select * from users u inner join "+
      "(select user_id, count(id) cnt from applications "+
      "where id in (select id from applications where "+
      "created_at > current_date - interval '1 week') "+
      "group by user_id) a on u.id = a.user_id order by a.cnt desc";
  var self = this;
  return new Promise(function _promise(resolve, reject) {
    req.client.query(queryString, [], function result(error, result) {
      req.done(error);

      if (error) {
        console.log('error ' + error.message);
        return reject(error);
      }
      var users = result.rows.map(function(row) {
        return new User(row);
      });
      resolve(users);
    });
  });

The above pattern is my every method the only thing that varies is the content after if, is there any functional approach I can use to refactor it out?

Adding one more example:

  var queryString = 'select c.id, c.name, t.contact_user '+
    'from companies c, teams t '+
    'where t.user_id = $1::int and t.company_id = c.id '+
    'limit $2::int';
  var self = this;
  return new Promise(function _promise(resolve, reject) {
    req.client.query( queryString, [self.id, User._RESOURCE_LIMIT],
        function result(error, result) {
      req.done(error);
      if (error) {
        console.log('Error ' + error.message);
        return reject(error);
      }

      self._companies = result.rows.map(function (data) {
        return new Company(data);
      });
      resolve(self);
    });
  });
2
  • 1
    so you always resolve(users)? that seems unlikely Commented Feb 28, 2017 at 3:51
  • @JaromandaX I think that will be variable too, let me correct the description. Commented Feb 28, 2017 at 3:55

2 Answers 2

1

Promisified "query" function

let query = (req, queryString, arg = []) => new Promise((resolve, reject) => {
    req.client.query(queryString, arg, (error, result) => {
        req.done(error);
        if (error) {
            return reject(error);
        }
        resolve(result);
    });
});

Usage (as per example in the question)

query(req, "select * .... etc")
.then(result => {
    return result.rows.map(function(row) {
        return new User(row);
    });
})
.catch(reason => {
    // error handling goes here
});
Sign up to request clarification or add additional context in comments.

5 Comments

The array after queryString will not be always empty, but yes I got your point.
another argument then - let me rewrite it
If the ES2015+ code isn't to your liking, I can transpile it for you :p
Its fine, I can infer it.
I think you can help me out in this codereview.stackexchange.com/q/156417/58341
0

You can do something like this:

function queryDb(queryString, arr) {
    var arr = arr || [];
    return new Promise(function _promise(resolve, reject) {
        req.client.query(queryString, arr, function result(error, result) {
            req.done(error);
            if (error) {
                console.log('Error ' + error.message);
                return reject(error);
            }
            resolve(result);
        });
    });
}

queryDb("queryString", arr).then(function(response){ //calling the function everytime like this
    //do stuff here
}, function(error){
    //handle error
})

1 Comment

Don't log the error here. Just reject it and allow it to be logged by the error handler, if desired.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.