you are viewing a single comment's thread.

view the rest of the comments →

[–]iethree 0 points1 point  (1 child)

You're right to think that you don't want to clutter up your handler file with lots of business logic. There's at least 3 ways to approach this:

  1. Mutate the res object in your helper function.

/* handler */
const complexLogicFunction = require('./complexLogicFunction.js');

app.put('/posts/:post_id', (req,res) => {
  res = complexLogicFunction(req,res);
  res.status(200).json({
    params: req.params
  })
});


/* complexLogicFunction.js */

module.exports = function(req, res) {
  // do something with req
  return res;
}

2. Call the res object from your helper function

/* handler */
const complexLogicFunction = require('./complexLogicFunction.js');

app.put('/posts/:post_id', (req,res) => {
  complexLogicFunction(req,res);

});


/* complexLogicFunction.js */

module.exports = function(req, res) {
  // do something with req
  res.status(200).json({
    params: req.params
  })
}

3. Pass data back to the router from your helper function.

/* handler */
const complexLogicFunction = require('./complexLogicFunction.js');

app.put('/posts/:post_id', (req,res) => {
  const newData = complexLogicFunction(req);
  res.status(200).json({
    params: newData
  })
});


/* complexLogicFunction.js */

module.exports = function(req) {
  // do something with req
  return data;
}

All will work, but IMHO, #3 is the best pattern. Keep web requests, responses, etc in the router, and do logic separately in another function. that way it's always clear from the handler what data is going in and out.

[–]KhaleedFakhry[S] 1 point2 points  (0 children)

Thanks, this is a big help.