There is REST endpoint in my application which handles POST request and then makes a HTTP post to another external application and when the resource is creating in the external resource then I create a record in my database with the externally created resource ID.

For example if a user requests to save a new Car then there is an endpoint which handles that request, calls external registration API to create a new registration number and then populates my database with the new car and the registration ID that I got from that API.

My question is where should I put theses two logic?

Let my controller handle the post request from user and call the external API and then when its successful then call my Car service to create a new car.

registrationID = registrationAPI.create() carService.create(registrationID)

OR

Let my controller delegate both the tasks to my car service and wait for the result, internally the car service handles both the calls, eg: carService.create(Car car)

Is there better ways to handle both the cases?

up vote 7 down vote accepted

Your controller should do one thing and do it well.

Creating a remote resource requires to handle and parse the request, then to handle remote creation, then to do the db stuff. This seems too much responsibilty for your controller alone.

In fact create a new (external) domain resource should involve the domain layer (exposed via the service layer). The domain layer would subcontract the remote handling and the persistance to some gateway objects. The front controller should only act as request handler.

Most of the links above refer to Martin Fowler's patterns of enterprise application architecture, which handles this kind of architectural aspects in full depth.

  • 1
    +1 for well researched answer. I'd suggest that the OPs statement about "wait for a response" is also a dial to tune. In many cases that will be a massive UX hit, and your recommendation of a front controller could make that less so by simply responding immediately that the request was received and letting the resource be populated asynchronously. – Paul Sep 17 '17 at 11:23

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.