How to validate response object in Spring WebClient

Viewed 1247

I am using Springs' Webclient to make a HTTP GET call.

How can I validate the response object GetPersonBasicInfoResWrapper's property that I received as a response of my HTTP call.

I am trying to validate the birthDate inside the flatMap by blocking the response object, but it doesn't look like the most functional way of doing it.

Following is the excerpt from my code.

private Mono<GetPersonBasicInfoResWrapper> getPersonBasicInfo(Double personId, LocalDate birthDate,
            CallerRequestMetaData callerInfo) {
        return middlewareWebClient
                .get()
                .uri(...)
                ...
                ...
                .exchange()
                .flatMap(client -> {
                    GetPersonBasicInfoResWrapper block = client.bodyToMono(GetPersonBasicInfoResWrapper.class).block();
                    
                    LocalDate personBirthDate = LocalDateTime.ofInstant(block.getBirthDate().toInstant(),ZoneId.of(Constants.DEFAULT_TIME_ZOME)).toLocalDate();
                    
                    if (!personBirthDate.equals(birthDate))
                        throw new YakeenRowadException(Errors.INCORRECT_ID_BIRTH_DATE_G, birthDate.toString()); 
                    else
                        return client.bodyToMono(GetPersonBasicInfoResWrapper.class);
                });
}

Any help is highly appreciated.

1 Answers

Try something like this

private Mono<PersonInfo> getPersonInfo(Double personId) {
    return webClient.get()
            .uri(...)
            .exchange()
            .flatMap(response -> {
                return response.bodyToMono(PersonInfo.class);
            });
}

private LocalDate toLocalDate(Instant instant) {
    return LocalDateTime.ofInstant(instant, ZoneId.of(Constants.DEFAULT_TIME_ZOME))
                        .toLocalDate();
}

public Mono<PersonInfo> doSomething(Double personId, LocalDate birthDate) {
    return getPersonInfo(personId)
             .flatMap(personInfo -> {
                final LocalDate birthDate = toLocalDate(personInfo.getBirthDate().toInstant());
                if (!personBirthDate.equals(birthDate)) { 
                    return Mono.error(new YakeenRowadException(Errors.INCORRECT_ID_BIRTH_DATE_G, birthDate.toString()));
                }
                return Mono.just(personInfo);
            });
}

Don't validate during the fetch, validation is business logic, and should be in the layer above.

  1. you fetch and return
  2. you validate.
  3. If validation fails, you return a Mono.error() to the calling client.

I have no idea what "MetaData" was supposed to be. I hope it's not the url, because passing it that way is wrong.

(try to avoid verbose naming)

Related