51 lines
2.0 KiB
Java
51 lines
2.0 KiB
Java
package tk.antoine.roux.infrastructure.in;
|
|
|
|
import io.vavr.control.Either;
|
|
import io.vavr.control.Option;
|
|
import org.jetbrains.annotations.NotNull;
|
|
import org.springframework.http.HttpStatus;
|
|
import org.springframework.http.ProblemDetail;
|
|
import org.springframework.http.ResponseEntity;
|
|
import org.springframework.web.bind.annotation.GetMapping;
|
|
import org.springframework.web.bind.annotation.RequestMapping;
|
|
import org.springframework.web.bind.annotation.RequestParam;
|
|
import org.springframework.web.bind.annotation.RestController;
|
|
import tk.antoine.roux.domain.usecases.Command;
|
|
import tk.antoine.roux.domain.usecases.Command.EmptyCommand;
|
|
import tk.antoine.roux.domain.usecases.operation.GetNodesUseCase;
|
|
|
|
import java.util.Optional;
|
|
|
|
@RestController
|
|
@RequestMapping("${backoffice.configuration.api-prefix}/v1")
|
|
public class NodeController {
|
|
|
|
private static final EmptyCommand EMPTY_COMMAND = new EmptyCommand();
|
|
private static final String LIST_NODES_ERROR_MESSAGE = "List nodes failed";
|
|
private final GetNodesUseCase getNodesUseCase;
|
|
|
|
public NodeController(GetNodesUseCase getNodesUseCase) {
|
|
this.getNodesUseCase = getNodesUseCase;
|
|
}
|
|
|
|
@GetMapping("/nodes")
|
|
ResponseEntity<?> listNode(@RequestParam(required = false, value = "criteria") Optional<Criteria> optionalCriteria) {
|
|
return Option.ofOptional(optionalCriteria)
|
|
.map(criteria -> criteria.toCommand().map(Command.class::cast))
|
|
.toEither(EMPTY_COMMAND)
|
|
.getOrElseGet(Either::right)
|
|
.map(getNodesUseCase::invoke)
|
|
.mapLeft(NodeController::exceptionToProblemDetail)
|
|
.fold(problemDetail -> ResponseEntity.of(problemDetail).build(), ResponseEntity::ok);
|
|
}
|
|
|
|
@NotNull
|
|
private static ProblemDetail exceptionToProblemDetail(Exception e) {
|
|
ProblemDetail problemDetail = ProblemDetail
|
|
.forStatusAndDetail(HttpStatus.BAD_REQUEST, e.getMessage());
|
|
problemDetail.setTitle(LIST_NODES_ERROR_MESSAGE);
|
|
return problemDetail;
|
|
}
|
|
|
|
}
|