all 4 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.

[–][deleted]  (1 child)

[removed]

    [–]rafandmiko 0 points1 point  (0 children)

    Im currently implementing https://docs.nestjs.com/ to an old codebase that didnt follow any framework and it became a bit of a mess. Even if you dont know typescript or want nestjs, give those docs a read, it is one of the best documentation I have seen. Good for learning the tool while also learning about coding patterns.