Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change body of ServerWebExchange response in WebFilter

I am trying to make an application in spring webflux. But there is a lot of stuff that I can't find in the documentation.
I have a webfilter where I want to add a wrapper around the response. Example:
Reponse before:

{
    "id": 1,
    "name": "asdf"
}

Response after:

{
    "status": "success",
    "data": {
        "id": 1,
        "name": "asdf"
    }
}

This is the WebFilter at the moment:

@Component
public class ResponseWrapperFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
        // Add wrapper to the response content...

        return webFilterChain.filter(serverWebExchange);
    }
}

But I can't find a way to get or edit the body of the response.
How can I change the response output in a WebFilter?

like image 939
Jan Wytze Avatar asked Nov 15 '17 19:11

Jan Wytze


1 Answers

As stated in the javadoc, WebFilter is made for application-agnostic, cross-cutting concerns. WebFilters usually mutate the request headers, add attributes to the exchange or handle the response altogether without delegating to the rest of the chain.

I don't think that what you're trying to achieve is easily doable or even something that should be achieved this way. At the raw exchange level, you're dealing with a Flux<DataBuffer>, which is the response body split randomly in groups of bytes.

You could somehow wrap the response in a filter and use Flux.concat to prepend and append data to the actual response written by the handler. But there are a lot of questions regarding encoding, infinite streams, etc.

Maybe this is a concern that should be achieved at the Encoder level, since there you could restrict that behavior to a particular media type.

like image 124
Brian Clozel Avatar answered Sep 18 '22 10:09

Brian Clozel