mercredi 24 février 2021

Writing a flexible and clean method to handle multiple REST API calls in Spring

To set up the problem, let's imagine we have a downstream service that we need to call for some information. We set up an API endpoint and call another method which will hold our business logic and make the HTTP request. Based off of certain parameters that were sent to this method, we may potentially have to make several calls to the same endpoint, depending on what it returns. The method is currently setup like so:

public HttpEntity<String> getInfo(//parameters) {
    
    //setup HTTP headers etc.
    HttpEntity response = restTemplate.exchange(//stuff here);

    //based off of on the parameters given to this method, we will know whether or not we need to make additional calls
    //if we DO need to make additional calls, we will also need to inspect the response for information
    //this is difficult, because as you see below, this method doesn't start to procces the response until after error checking
    
    //do all error checking ie. checking for no data and other HTTP errors
    
    OurDataClass dataClass = objectmapper.writeValueasString(response.getBody());
    //do things to dataClass
    return new HttpEntity<String>(//dataClass and headers);

Given the current structure of this method, I don't know how to work it into something that's more extendable and maintainable. My first instinct was to just encapsulate the restTemplate and take care of additional calls there, but given the fact that I need to inspect the request contents of each call, something that is not done until the end of the current method, it would seem like we're doing a lot of double work. On the other hand, working the solution into the method without any encapsulation would make it even more difficult to maintain down the road (it's already a bit of a mess with error checking).

Am I overthinking it? Is it wrong to try to shoehorn in some sort of design pattern here?

Aucun commentaire:

Enregistrer un commentaire