1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.bremersee.apiclient.webflux.contract;
18
19 import static java.util.Objects.nonNull;
20 import static org.springframework.core.GenericTypeResolver.resolveReturnTypeArgument;
21
22 import java.lang.reflect.Method;
23 import java.util.function.BiFunction;
24 import org.bremersee.apiclient.webflux.Invocation;
25 import org.reactivestreams.Publisher;
26 import org.springframework.web.reactive.function.client.WebClient.ResponseSpec;
27 import reactor.core.publisher.Flux;
28 import reactor.core.publisher.Mono;
29
30
31
32
33
34
35 public class ResponseFunction implements BiFunction<Invocation, ResponseSpec, Publisher<?>> {
36
37 @Override
38 public Publisher<?> apply(Invocation invocation, ResponseSpec responseSpec) {
39
40 Method method = invocation.getMethod();
41 Class<?> responseClass = method.getReturnType();
42 if (Mono.class.isAssignableFrom(responseClass)) {
43 Class<?> typeClass = resolveReturnTypeArgument(method, responseClass);
44 return nonNull(typeClass)
45 ? responseSpec.bodyToMono(typeClass)
46 : responseSpec.bodyToMono(responseClass);
47 }
48 if (Flux.class.isAssignableFrom(responseClass)) {
49 Class<?> typeClass = resolveReturnTypeArgument(method, responseClass);
50 return nonNull(typeClass)
51 ? responseSpec.bodyToFlux(typeClass)
52 : responseSpec.bodyToFlux(responseClass);
53 }
54 if (Publisher.class.isAssignableFrom(responseClass)) {
55 Class<?> typeClass = resolveReturnTypeArgument(method, responseClass);
56 return nonNull(typeClass)
57 ? responseSpec.bodyToFlux(typeClass)
58 : responseSpec.bodyToFlux(responseClass);
59 }
60 throw new IllegalStateException(
61 "Response class must be Mono, Flux or Publisher.");
62 }
63 }