I want to create a conditional WebFilter
that executes one logic if ServerWebExchangeMatcher
matches, and another logic if it does not match.
The following already works for a "positive" match, by using .filter(..::isMatch)
. But how could I add a .orElse()
method here into the flow?
class PathFilter implements org.springframework.web.server.WebFilter {
private ServerWebExchangeMatcher paths;
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
//TODO how to add a "no-match" execution?
return this.paths.matches(exchange)
.filter(ServerWebExchangeMatcher.MatchResult::isMatch)
.flatMap(...)
.then();
}
}
So what @123 probably means is the following:
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return this.paths.matches(exchange)
.flatMap((matchResult) ->
matchResult.isMatch()
? customLogic(exchange, chain)
: chain.filter(exchange)) //continue normal flow
.then();
}
Which works, but I'd still be interested if there is a possibility to delegate a "negative-match" outcome directly inside the flow, maybe with switchIfEmpty()
or similar.
One of the solution for above one is "switchIfEmpty()" can be added in case filter condition become false. Please let me know if you fave any further question on this.
class PathFilter implements org.springframework.web.server.WebFilter {
private ServerWebExchangeMatcher paths;
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
//TODO how to add a "no-match" execution?
return this.paths.matches(exchange)
.filter(ServerWebExchangeMatcher.MatchResult::isMatch)
.flatMap(...)
.switchIfEmpty(Mono.defer(() -> doSomethingElse()));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With