简体   繁体   中英

Node.js using res and req in Services

I have a general question on how you handle services and routes in node.js. Would you handle the response directly in the service or would you leave that to the route? Here's what i mean in code

Like this

Route

router.get('/', (req, res, next) ==> {
   someService.someMethod(req, res);
});

Service

const someMethod = (req, res) => {
   try {
      var something = await someOtherMethod(req.body.someParameter);
      return res.status(200).send(something.data);
   } catch (err) {
      return res.status(500).send({msg: err.message});
   }
}

Or this

Router

router.get('/', (req, res, next) ==> {
   try {
      var something = await someService.someMethod(req.body.someParameter);
      res.status(200).send(something.data);
   } catch (err) {
      res.status(500).send({msg: err.message})
   }
});

Service

const SomeMethod = (Input) => {
   return someOtherMethod(Input);
}

The first way would make the routers much simpler and cleaner especially if the use the service in multiple routes, but on the downside I always need to supply the res and req and I will run into problems if I want to use the service internally. I'm tending to the second method.

How do you design your services?

I would go for router.get('/', RootController)

const RootController = (req, res) => {
    // extract what you need from the request
    const param = req.body.param;

    // calculate what you need in a pure function `businessLogic`
    const result = businessLogic(param);

    // send the response
    return res.send(result);
}

This way you get a separation of concerns - your root controller is responsible only for handling / requests - getting a response for a request. All "business logic" is done in a pure function (you can easily test it without any HTTP request contexts/mocks, it can be reused somewhere else, for example in different controller).

I use the following architecture: 1. Route 2. Controller 3. Services

Your route is the one validating the input, your controller is the one handling all the logics and calling the services and returning the final result to your route.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM