Created
March 27, 2019 15:04
-
-
Save lucianenache/a4235867c48e20c4117c812e446a77be to your computer and use it in GitHub Desktop.
Spring Boot procedural, lambda and reactive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Procedural endpoint */ | |
@GetMapping("/users/{id}") | |
ResponseEntity<User> get(@PathVariable long id) { | |
User user = repository.findById(id); | |
if(user != null) { | |
return ok(user); | |
} else { | |
return notFound(); | |
} | |
} | |
/* Lambda endpoint */ | |
@GetMapping("/users/{id}") | |
ResponseEntity<User> get(@PathVariable long id) { | |
return repository | |
.findById(id) | |
.map(user -> ok(user)) | |
.orElse(notFound()); | |
} | |
/* Reactive endpoint - SpringBoot2 webflux */ | |
@Bean | |
RouterFunction<ServerResponse> route() { | |
return route( | |
GET("/users/{id}"), request -> Mono | |
.justOrEmpty(request.PathVariable("id")) | |
.map(Long::parseLong) | |
.flatMap(id -> repository.findById(id) | |
.flatMap(p -> ok().body(fromObject(p)) | |
.switchIfEmpty(notFound().build()))) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment