I have method:
@GetMapping
public Either<ResponseEntity<TaskError>,ResponseEntity<List<TaskDto>>> readAllOrderedByStatus() {
var result = taskCrudService.readAllOrderedByStatus();
if (result.isLeft()) {
return Either.left(
new ResponseEntity<>(
TaskError.TASKS_LIST_NOT_FOUND,
HttpStatus.NOT_FOUND));
}
return Either.right(new ResponseEntity<>(result.get(),HttpStatus.OK));
}
I want to return List and HTTP status or TaskError.TASKS_LIST_NOT_FOUND and HTTP status, but due to Either there are also additional things in Json like "right" etc.
Solution (thanks @chrylis -cautiouslyoptimistic)
@GetMapping
public ResponseEntity<?> readAllOrderedByStatus() {
var result = taskCrudService.readAllOrderedByStatus();
return taskCrudService
.readAllOrderedByStatus()
.fold(
error -> new ResponseEntity<>(error,HttpStatus.NOT_FOUND),
list -> new ResponseEntity<>(list,HttpStatus.OK));
}
I'm using Either for exactly this kind of concept in a REST API. You will need to be responsible for converting your Either into a consistent response. In most cases, including yours, you're needing fold
:
return taskCrudService.readAllOrderedByStatus() // -> Either
.fold(
__ -> ResponseEntity.notFound(TASKS_LIST_NOT_FOUND).build(),
list -> ResponseEntity.ok(list)
);