Skip to content

Instantly share code, notes, and snippets.

@lucianenache
Created March 27, 2019 15:04
Show Gist options
  • Save lucianenache/a4235867c48e20c4117c812e446a77be to your computer and use it in GitHub Desktop.
Save lucianenache/a4235867c48e20c4117c812e446a77be to your computer and use it in GitHub Desktop.
Spring Boot procedural, lambda and reactive
/* 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