Search code examples
springwebclientresttemplatereactor

How to replace a resttemplate implementation with webclient


I'm trying to replace a resttemplate implementation with a webclient one. The tricky stuff here is that I need to modify a property from an input object, when the response resolves. I don't find the way to achieve it...

This is the resttemplate code:

public Instance login(final Instance instancia, final LoginDTO dto) {
        String url = instancia.getBalancer() + API_AUTHENTICATE_PATH;
        HttpEntity<LoginDTO> request = generateRequest(dto);
        ResponseEntity<JWTToken> token = restTemplate.postForEntity(url, request, JWTToken.class);
        instancia.setToken(token.getBody().getIdToken());
        return instancia;   
}

And this is what I have until now:

    @Override
    public Mono<Instance> login(Instance instancia, LoginDTO dto) {

        Mono<JWTToken> monoToken=webClient.post().uri(url).body((BodyInserters.fromObject(dto))).retrieve()
        .bodyToMono(JWTToken.class);

        return {....};

    }

I'm stucked in that part, because I don't find the way to alter the Instance object...

And there is another point: This is injected in another class, because I need to run this request in parallel against multiple targets. So, a block call is not enough.

Does someone have an idea about how to do it?

Thanks a lot in advance!


Solution

  • It can be achieved easily as following:

    @Override
    public Mono<Instance> login(Instance instancia, LoginDTO dto) {
        return webClient
                .post()
                .uri(url)
                .body((BodyInserters.fromObject(dto)))
                .retrieve()
                .bodyToMono(JWTToken.class)
                .map(token -> {
                    instancia.setToken(token.getBody().getIdToken());
                    return instancia;
                });
    }