Return 休息时 (Vavr) api

Return Either (Vavr) in rest api

我有方法:

@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));
}

我想 return 列出和 HTTP 状态或 TaskError.TASKS_LIST_NOT_FOUND 和 HTTP 状态,但由于 Either Json 中还有其他内容,例如“正确”等

解决方案(感谢@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));
}

我将 Either 用于 REST API 中的此类概念。您需要负责将 Either 转换为一致的响应。在大多数情况下,包括您的情况,您需要 fold:

return taskCrudService.readAllOrderedByStatus() // -> Either
  .fold(
    __   -> ResponseEntity.notFound(TASKS_LIST_NOT_FOUND).build(),
    list -> ResponseEntity.ok(list)
  );