title: Reactive Spring Query Parameters
body: <p>My Spring Reactive Web API should be able to filter based on query parameters but I'm struggling to get this right.</p>
  
  <pre><code>GET /v1/address?type=business
  </code></pre>
  
  <p>Should return all addresses of type 'business' in the system (just an example since I'm not posting the actual requirements). If the parameter is absent then just return all addresses.</p>
  
  <pre><code>[
    { "id" : 1, "type" : "business", "street" : "..."},
    { "id" : 2, "type" : "business", "street" : "..."},
    ...
  }
  </code></pre>
  
  <p>I'm using Router functions to map the request:</p>
  
  <pre><code>public RouterFunction&lt;ServerResponse&gt; route(AddressHandler handler) {
      return route(GET("/v1/address"), handler::getAddresses);
  }
  </code></pre>
  
  <p>But I'm struggling to determine how to check for the parameter and, if it isn't present, to return all addresses.</p>
  
  <pre><code>class AddressHandler {
      Mono&lt;ServerResponse&gt; getAddressesFilteredOrNot(ServerRequest request) {
          Optional&lt;String&gt; addressType = request.getQueryParam("type");
  
          ...
      }
  }
  </code></pre>
  
  <p>Now the Optional.ifPresent() isn't going to work, I can't return from the method:</p>
  
  <pre><code>class AddressHandler {
      Mono&lt;ServerResponse&gt; getAddressesFilteredOrNot(ServerRequest request) {
          Optional&lt;String&gt; addressType = request.getQueryParam("type");
  
          // invalid
          addressType.ifPresent(addrType -&gt; {
              return ServerResponse.ok()
                  .body(this.service.getAddressByType(addrType),
                     Address.class);
      });
  }
  </code></pre>
  
  <p>Also I can't switchIfEmpty() on the parameter since it throws a NullPointerException:</p>
  
  <pre><code>class AddressHandler {
      Mono&lt;ServerResponse&gt; getAddressesFilteredOrNot(ServerRequest request) {
          Optional&lt;String&gt; addressType = request.getQueryParam("type");
  
          // also invalid
          return Mono.justOrEmpty(addressType.orElse(""))
                 .flatMap(addrType -&gt; ServerResponse.ok().body(this.service.getAddressByType(addrType), Address.class)
                 .switchIfEmpty(ServerResponse.ok().body(this.service.getAllAddresses(), Address.class));
      });
  }
  </code></pre>
  
  <p>What's the flow to use query parameters if they are present and fall back on the getAllAddresses() method? Is it actually possible?</p>