Custom callback in Express.js get

I have my app.js

app.get('/api/personnel', api.personnel);

      

which calls this function as a callback to load some data from mongo:

exports.personnel = function(req, res) {
  var docs;
  db.personnel.find(function(err, docs) {
    if (err) {
      logError(err);
    } else {
      res.json({
        personnel: docs
      });
    }
  });

};

      

This works great, but I would really like to be able to call a callback for testing purposes when the function is complete:

exports.personnel = function(req, res, callback) {
  var docs;
  db.personnel.find(function(err, docs) {
    if (err) {
      logError(err);
    } else {
      res.json({
        personnel: docs
      });
    }
    callback();
  });

      

callback()

is empty when the function is called from a real application and gives me an error:

Error: Can't set headers after they are sent.

      

How do I get the get call?

+1


source to share


2 answers


You can simply wrap this function to insert an additional function argument:



exports.personnel = function(req, res, callback) {
  var docs;
  db.personnel.find(function(err, docs) {
    if (err) {
      logError(err);
    } else {
      res.json({
        personnel: docs
      });
    }
  });
///////////////////////////////////////////////////

var callback = ...;
pp.get('/api/personnel', function(req, res) {
     api.personnel(req, res, callback);
});

      

+2


source


the third line in Express is always reserved for callbacks next()

(as shown in middlewares). If you want to have a "callback" but don't want to mess up the expression, let the hack!

exports.personnel = function(req, res, callback) {
  var docs;
  db.personnel.find(function(err, docs) {
    if (err) {
      logError(err);
    } else {
      res.json({
        personnel: docs
      });
    }
    if(process.env.NODE_ENV === 'test')
      callback();
  });

      



then when you want to test, export NODE_ENV=test

in your shell

0


source







All Articles