Skip to content

Instantly share code, notes, and snippets.

@dniel
Created June 7, 2019 08:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dniel/e32d38d22f4214b046c341ffe66e71c4 to your computer and use it in GitHub Desktop.
Save dniel/e32d38d22f4214b046c341ffe66e71c4 to your computer and use it in GitHub Desktop.
VavrExample
private static final Logger LOGGER = LoggerFactory.getLogger(BoostResource.class);
private final SomethingCommandHandler handler;
@Autowired
public SomeResource(SomethingCommandHandler handler) {
this.handler = handler;
}
@RequestMapping(value = "/api", method = RequestMethod.POST)
public ResponseEntity<Object> api(@RequestBody RequestValues request) {
LOGGER.info("Boost called with request: {}", request);
SomethingCommand operation = createCommand(request);
Try<Object> operationTry = handler.perform(operation)
.onSuccess(r -> LOGGER.info("Success"))
.onFailure(e -> LOGGER.error("Failure", e));
return Match(operationTry).of(
Case($Success($()), o -> ResponseEntity.ok(o)),
Case($Failure($()), e -> ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build())
);
}
/**
* Validate and create API operation parameter object.
*
* @param request parsed from http request.
* @return SomethingCommand operation parameter object.
* @throws InvalidOperationException if operation could not be validated.
*/
private SomethingCommand createCommand(RequestValues request) {
Consumer<List<RequestValue>> warnIfEmpty = elements -> {
if (elements.isEmpty()) {
LOGGER.warn("No values found in API call.");
}
};
CheckedFunction0<List<RequestValue>> values = () -> List.ofAll(request.getValues());
CheckedFunction1<List<RequestValue>, RequestValue> findFirst = elements -> elements.get(0);
CheckedFunction1<RequestValue, SomethingCommand> SomethingCommand = SomethingCommandMapper::toOp;
return Try.of(values)
.peek(warnIfEmpty)
.mapTry(findFirst)
.mapTry(SomethingCommand)
.toOption()
.getOrElseThrow(InvalidOperationException::new);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment