maudulus
maudulus

Reputation: 11045

Response from node app returns nothing, but should return array

I am testing a nodeJS server, built on the express framework.

When a request is sent to the server, the server should send back some data, in the form of an array. Instead, it is sending back ''.

The test that I am trying to pass is as follows:

it('should send postgres data to the server', function(done) {
  request(app)
  .post('/chart')
  .send({min:"1",max:"100",arrayLength:"12"})
  .expect(200, sqlData)
  .end(function(err, res){
    if(err) {
      done(err);
    } else {
      done();
    }
  });
});

Note that sqlData is equal to what the sent response should be.

When the router receives a POST request it does the following:

router.post('/', function(req, res) {
    res.send(randomSqlTableSelector(req.body.min,req.body.max,req.body.arrayLength));
});

I have checked that req.body.min, max and arrayLength are all the numbers that I would expect them to be.

Thus, the problem is likely in my function randomSqlTableSelector, which, for whatever reason, when called inside of the router, simple returns the empty quotes ''

The function is as follows:

function randomSqlTableSelector(min,max,arrayLength) {
    var filledArray = [];
    pg.connect(conString, function(err, client, done) {
        if(err) {
            return console.error('error fetching client from pool', err);
        }
        client.query('SELECT cell1 FROM random AS retrievedNumber;', function(err, result) {
            var psqlData = result.rows;
            for (i in psqlData) {
                filledArray.push(psqlData[i]["cell1"])
            }
            return filledArray
        });
    });
}

Upvotes: 0

Views: 448

Answers (1)

mscdex
mscdex

Reputation: 106746

You cannot treat functions that perform asynchronous, non-blocking tasks as synchronous and blocking. Try passing in a callback instead:

function randomSqlTableSelector(min, max, arrayLength, cb) {
  pg.connect(conString, function(err, client, done) {
    if (err)
      return cb(err);
    client.query('SELECT cell1 FROM random AS retrievedNumber;', function(err, result) {
      if (err)
        return cb(err);
      var psqlData = result.rows,
          filledArray = [],
          i;
      for (i in psqlData)
        filledArray.push(psqlData[i]["cell1"])
      cb(null, filledArray);
    });
  });
}

Then use it in your route like:

router.post('/', function(req, res) {
  var min = req.body.min,
      max = req.body.max,
      len = req.body.arrayLength;
  randomSqlTableSelector(min, max, len, function(err, array) {
    if (err) {
      console.log(err);
      return res.send(500);
    }
    res.send(array);
  });
});

Upvotes: 2

Related Questions