Implementation of controllers

The following is MovieController, which caters for listing and rating movies:

@RequestMapping("/movies")
@RestController
class MovieController constructor(val movieService : MovieService) {

@GetMapping
fun getMovies() : Flux<Movie> {
return this.movieService.findAll();
}

@GetMapping("/{id}")
fun getMovie(@PathVariable id : Int) : Mono<Movie> {
return this.movieService.findOne(id);
}

@PutMapping("/{id}/rate")
fun rateMovie(@PathVariable id : Int, @RequestParam rating : Int,
@RequestParam
comment : String) : Mono<Movie> {
return this.movieService.rate(id, comment, rating);
}
}

The getMovies function is mapped to the /movies URL and will load movies from MongoDB by using the MovieService.findAll() function as Flux<Movie> and sending it as a JSON response to the caller.

The getMovie function is mapped to the /movies/{id} URL and will load the movie identified by the id path variable from MongoDB by using the MovieService.findOne() function as Mono<Movie> and sending it as a JSON response to the caller.

The rateMovie function is mapped to the /movies/{id}/rate URL and will load the movie identified by the id path variable from MongoDB and rate it with the comment and rating query strings passed in by using the MovieService.rate() function as Mono<Movie> and sending it as a JSON response to the caller.

Furthermore, to show meaningful information when MovieNotFoundException is thrown instead of a white label page, ErrorDTO is introduced as follows:

data class ErrorDTO(val code : Int, val message : String?) : Serializable

This has the code phrase, which is the HTTP status code, and a message property. A @ControllerAdvice is used to catch MovieNotFoundException and convert it to a ReponseEntity containing ErrorDTO, as follows:

@ControllerAdvice
class BaseController {

@ExceptionHandler(value = MovieNotFoundException::class)
fun handleMovieNotFoundException (e : MovieNotFoundException) :
ResponseEntity<ErrorDTO> {
return ResponseEntity<ErrorDTO>(ErrorDTO(400, e.message),
HttpStatus.BAD_REQUEST);
}
}

The handleMovieNotFoundException function accepts an argument of MovieNotFoundException and is annotated with @ExceptionHandler to catch that exception. Inside the function, the correct message and HTTP status code are returned as part of ErrorDTO.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.105.31