Reputation: 86925
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();
}
}
Upvotes: 4
Views: 4080
Reputation: 197
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()));
}
}
Upvotes: 1
Reputation: 86925
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.
Upvotes: 3