Search code examples
javapostwebclientcode-cleanup

Java Mapping Web Client POST request to different objects without copy the code


I have a post request which I want it to map the response to different objects for 2 api who call it. The request always return BookResponse.

Here I map the response to return the book name:

public Mono<String> getBookName(BookRequest bookRequest) {
  return client
            .post()
            .uri("PATH")
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON_UTF8)
            .body(bookRequest))
            .retrieve()
            .bodyToMono(BookResponse.class)
            .doOnNext(this::validateResponseStatus)
            .map(BookResponse::getBookName)
            .doOnError(throwable -> logError(throwable));
 }

and here same call just map the response to other Object which contains the book author + the request object:

 public Mono<BookObject> getBookName(BookRequest bookRequest) {
        return client
            .post()
            .uri("PATH")
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON_UTF8)
            .body(requestBody))
            .retrieve()
            .bodyToMono(BookResponse.class)
            .doOnNext(this::validateResponseStatus)
            .map(bookResponse -> new BookObject(bookResponse.getName(), bookRequest)
            .doOnError(throwable -> logError(throwable));

Is there a way to do it without copy the code? Thanks


Solution

  • I would extract the common code into a separate method:

    public Something getSomething() {
      client
            .post()
            .uri("PATH")
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON_UTF8)
            .body(requestBody))
            .retrieve()
            .bodyToMono(BookResponse.class)
            .doOnNext(this::validateResponseStatus)
    

    }

    Then, in your methods you simply need to do something like:

    Something something = getSomething();
    return something.map(bookResponse -> new BookObject(bookResponse.getName(), bookRequest).doOnError(throwable -> logError(throwable));
    

    or

    Something something = getSomething();
    return something.map(BookResponse::getBookName).doOnError(throwable -> logError(throwable));