Mo Hassan Mo Hassan - 14 days ago 10
Javascript Question

howto Node module.exports

I want to separate the code for executing mysql query in Node, so I am trying to use the Revealing Module pattern here

/* pool -create connection pool mysql*/
var sqlQuery = function (sqlString) {
var _result = pool.getConnection(function (err, connection) {
/* error handling*/
connection.query(sqlString, function (err, rows) {
console.log(this.sql);
if (!err) {
return _result = rows; <============
}
connection.release();
});
return;
});
console.log(_result);
return { recordSet : _result }
};
module.exports = sqlQuery;


How can I return rows to my app.js. the code below for calling sqlQuery is not working

var SqlQuery = require(./path/to/sqlQueryFile);
var rows = SqlQuery('pass sql here').recordSet;
console.log(row);
res.json(rows);

Answer

Your code is asynchronous, but you're calling it synchronously.

If you wanted to do it like this, you'll also need to pass a callback to SqlQuery.

/* pool  -create connection pool mysql*/
var sqlQuery = function (sqlString, callback) {
    var _result = pool.getConnection(function (err, connection) {
    /* error handling*/
      connection.query(sqlString, function (err, rows) {
        console.log(this.sql);
        if (!err) {
          callback(rows);
        } 
        connection.release();
      });
  });
};
module.exports = sqlQuery;

And then call it with:

var SqlQuery = require(./path/to/sqlQueryFile);
var rows = SqlQuery('pass sql here', function(recordSet){
  console.log(recordSet);
  res.json(recordSet);
});

Edit: If you're using newer versions of JavaScript, you have a few more options.

If you have access to Promises, you can do this:

function sqlQuery (sqlString) {
  return new Promise((resolve, reject) => {
    pool.getConnection(function (err, connection) {
      if (err) { return reject(err); } // error handling
      connection.query(sqlString, function (err, rows) {
        if (err) { return reject(err); }
        resolve(rows);
        connection.release();
      });
    });
  });
}
module.exports = sqlQuery;

And then you'd use it like:

var SqlQuery = require(./path/to/sqlQueryFile);
SqlQuery('pass sql here')
  .then(function(recordSet) {
    console.log(recordSet);
    res.json(recordSet);
  })
  .catch(function(err) {
    // do your error handling
    res.status(500).json({ err: 'Sorry there was an error' });
  });

If you're using even newer JavaScript, you can use the async/await syntax (currently available via Babel, and I think in FireFox. Chrome in V55).

var SqlQuery = require(./path/to/sqlQueryFile);
async handleQuery(query) {
  try {
      var rows = await SqlQuery(query);
      res.json(rows);
  } catch (e) {
    console.log('Error!', e);
  }
}

To chain multiple queries together:

async handleQuery(query) {
  try {
      return await SqlQuery(query);
  } catch (e) {
    console.log('Error!', e);
  }
}

var rows = await handleQuery('select * from tablename');
var rowsToReturn = await handleQuery('select id from another_table where name = "' + rows[0].name + '"');