I have been working on a sample reactive web api using Spring Boot 2.0.1 and its Webflux library. I have been looking at examples from online to try to build it, but I am stumped on two things. Below are the two questions I have.
1) How do I return a Flux of Response Entities, when I try I get an error saying that only a Single Response Entity can be returned. Below is my current code.
@Service
public class MovieServiceImpl implements MovieService {
@Autowired
private MovieRepository movieRepository;
@Override
public Flux<Movie> list(){
return movieRepository.findAll();
}
}
@RestController
public class MovieRestController {
@Autowired
private MovieService movieService;
@GetMapping(value = "/movies")
public Flux<Movie> list() {
return movieService.list();
}
}
2) When I Update an object I use a flatMap to update the object saved in Mongo, and then a Map to turn it to a Response Entity. My question is why am I using flatMap here instead of map? I derived this code from online examples, but no example explained the use of flatMap. I would like to understand why it is being used here. Below is the code.
@Service
public class MovieServiceImpl implements MovieService {
@Autowired
private MovieRepository movieRepository;
@Override
public Mono<Movie> update(String id, MovieRequest movieRequest) {
return movieRepository.findById(id).flatMap(existingMovie -> {
if(movieRequest.getDescription() != null){
existingMovie.setDescription(movieRequest.getDescription());
}
if(movieRequest.getRating() != null){
existingMovie.setRating(movieRequest.getRating());
}
if(movieRequest.getTitle() != null) {
existingMovie.setTitle(movieRequest.getTitle());
}
return movieRepository.save(existingMovie);
});
}
}
@RestController
public class MovieRestController {
@Autowired
private MovieService movieService;
@PutMapping("/movies/{movieId}")
public Mono<ResponseEntity<Movie>> update(
@PathVariable("movieId") final String movieId,
@RequestBody final MovieRequest movieRequest) {
return movieService.update(movieId, movieRequest)
.map(m -> new ResponseEntity<>(m, HttpStatus.OK))
.defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
}