11package graphql .kickstart .spring .webclient .boot ;
22
33import com .fasterxml .jackson .databind .ObjectMapper ;
4- import java .io .IOException ;
5- import java .io .InputStream ;
6- import java .nio .charset .StandardCharsets ;
74import java .util .List ;
85import java .util .Map ;
96import lombok .RequiredArgsConstructor ;
107import lombok .SneakyThrows ;
118import lombok .extern .slf4j .Slf4j ;
12- import org .springframework .core .io .ClassPathResource ;
13- import org .springframework .core .io .Resource ;
149import org .springframework .http .MediaType ;
15- import org .springframework .util .StreamUtils ;
1610import org .springframework .web .reactive .function .client .WebClient ;
1711import reactor .core .publisher .Flux ;
1812import reactor .core .publisher .Mono ;
@@ -40,15 +34,9 @@ private <T> T readValue(Object value, Class<T> returnType) {
4034 return objectMapper .convertValue (value , returnType );
4135 }
4236
43- @ SneakyThrows
44- private String loadQuery (String path ) {
45- return loadResource (new ClassPathResource (path ));
46- }
47-
48- private String loadResource (Resource resource ) throws IOException {
49- try (InputStream inputStream = resource .getInputStream ()) {
50- return StreamUtils .copyToString (inputStream , StandardCharsets .UTF_8 );
51- }
37+ @ Override
38+ public <T > Mono <T > post (GraphQLRequest <T > request ) {
39+ return execute (request ).map (it -> readValue (it , request .getReturnType ()));
5240 }
5341
5442 @ Override
@@ -66,15 +54,28 @@ public <T> Flux<T> flux(String resource, Map<String, Object> variables, Class<T>
6654 .map (it -> readValue (it , returnType ));
6755 }
6856
57+ @ Override
58+ @ SuppressWarnings ("unchecked" )
59+ public <T > Flux <T > flux (GraphQLRequest <T > request ) {
60+ Mono <Object > responseObject = execute (request );
61+ return responseObject .map (List .class ::cast )
62+ .flatMapMany (Flux ::fromIterable )
63+ .map (it -> readValue (it , request .getReturnType ()));
64+ }
65+
6966 private Mono <Object > execute (String resource , Map <String , Object > variables ) {
70- GraphQLRequest request = GraphQLRequest .builder ()
71- .query ( loadQuery ( resource ) )
67+ GraphQLRequest <?> request = GraphQLRequest .builder (Object . class )
68+ .resource ( resource )
7269 .variables (variables )
7370 .build ();
71+ return execute (request );
72+ }
7473
75- return webClient .post ()
76- .contentType (MediaType .APPLICATION_JSON )
77- .bodyValue (request )
74+ private Mono <Object > execute (GraphQLRequest <?> request ) {
75+ WebClient .RequestBodySpec spec = webClient .post ()
76+ .contentType (MediaType .APPLICATION_JSON );
77+ request .getHeaders ().forEach ((header , values ) -> spec .header (header , values .toArray (new String [0 ])));
78+ return spec .bodyValue (request .getRequestBody ())
7879 .retrieve ()
7980 .bodyToMono (GraphQLResponse .class )
8081 .flatMap (it -> Mono .justOrEmpty (it .getFirstObject ()));
0 commit comments