Kashyap
Kashyap

Reputation: 477

Need to invoke same controller method for different api's

I have 2 APIs

1. localhost:8080/myservice/foo/1/0/updatesStatus
2. localhost:8080/myservice/bar/1/0/updatesStatus

I am not allowed to have different controllers for each API. So both the APIs are pointing to the same controller method where I have if-else check, but the code looks very bad in that, is there any better way to handle this.

@PostMapping(value = UPDATE_STATUS_API_PATH)
public Response updateStatus(@PathVariable("group") String group , @RequestBody UpdateStatusRequest updateStatusRequest, HttpServletRequest request) {
        try {
            if(APIUrl.FOO_GROUP.equals(group)){
               //code spefic to foo
            }
            else{
              //code spefic to bar
            }
            //common code
}

The same conditional checks also have to be performed on the service layer as well. Is there any way I can avoid this conditional checks without having separate controller methods.

Upvotes: 1

Views: 675

Answers (1)

Smile
Smile

Reputation: 4088

I can think of this.

Create an interface for service.

public interface UpdateService {
    void updateStatus(UpdateStatusRequest updateStatusRequest);
}

Then you create different implementations.

public class FooUpdateService implements UpdateService  {
    void updateStatus(UpdateStatusRequest updateStatusRequest) {
        // foo specific logic
    }
}
public class BarUpdateService implements UpdateService  {
    void updateStatus(UpdateStatusRequest updateStatusRequest) {
        // Bar specific logic
    }
}

Create a UpdateServiceFactory

public class UpdateServiceFactory {
    @Autowired
    private UpdateService fooUpdateService;

    @Autowired
    private UpdateService fooUpdateService;

    public UpdateService getUpdateService(String group) {
        // Move the if-else logic here
        if(APIUrl.FOO_GROUP.equals(group)){
               return fooUpdateService;
            }
            else{
              //code spefic to bar
              return barUpdateService;
            }
    }
}

Controller:

@PostMapping(value = UPDATE_STATUS_API_PATH)
public Response updateStatus(@PathVariable("group") String group , @RequestBody UpdateStatusRequest updateStatusRequest, HttpServletRequest request) {
        updateServiceFactory.getUpdateService(group).updateStatus(updateStatusRequest);
            //common code
}

Upvotes: 1

Related Questions