Create webflux and webmvc sub-packages under ~.graphql

Allows simpler and consistent names for HTTP and WebSocket handler
classes for webmvc and webflux.
This commit is contained in:
Rossen Stoyanchev
2021-01-03 21:33:19 +00:00
parent 35c2068bdf
commit 63065d4e8e
11 changed files with 114 additions and 52 deletions

View File

@@ -28,8 +28,8 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.graphql.WebFluxGraphQLHandler;
import org.springframework.graphql.WebFluxGraphQLWebSocketHandler;
import org.springframework.graphql.webflux.GraphQLHttpHandler;
import org.springframework.graphql.webflux.GraphQLWebSocketHandler;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.HandlerMapping;
@@ -50,16 +50,16 @@ public class WebFluxGraphQLAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public WebFluxGraphQLHandler graphQLHandler(GraphQL.Builder graphQLBuilder) {
return new WebFluxGraphQLHandler(graphQLBuilder.build(), Collections.emptyList());
public GraphQLHttpHandler graphQLHandler(GraphQL.Builder graphQLBuilder) {
return new GraphQLHttpHandler(graphQLBuilder.build(), Collections.emptyList());
}
@Bean
@ConditionalOnMissingBean
public WebFluxGraphQLWebSocketHandler graphQLWebSocketHandler(
public GraphQLWebSocketHandler graphQLWebSocketHandler(
GraphQL.Builder graphQLBuilder, GraphQLProperties properties, ServerCodecConfigurer configurer) {
return new WebFluxGraphQLWebSocketHandler(
return new GraphQLWebSocketHandler(
graphQLBuilder.build(), Collections.emptyList(),
configurer, properties.getConnectionInitTimeoutDuration()
);
@@ -67,7 +67,7 @@ public class WebFluxGraphQLAutoConfiguration {
@Bean
public RouterFunction<ServerResponse> graphQLEndpoint(
WebFluxGraphQLHandler handler, GraphQLProperties properties, ResourceLoader resourceLoader) {
GraphQLHttpHandler handler, GraphQLProperties properties, ResourceLoader resourceLoader) {
String path = properties.getPath();
Resource resource = resourceLoader.getResource("classpath:graphiql/index.html");
@@ -80,7 +80,7 @@ public class WebFluxGraphQLAutoConfiguration {
@Bean
public HandlerMapping graphQLWebSocketEndpoint(
WebFluxGraphQLWebSocketHandler handler, GraphQLProperties properties) {
GraphQLWebSocketHandler handler, GraphQLProperties properties) {
String path = properties.getWebSocketPath();
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();

View File

@@ -28,7 +28,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.graphql.WebMvcGraphQLHandler;
import org.springframework.graphql.webmvc.GraphQLHttpHandler;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.RouterFunctions;
@@ -46,20 +46,20 @@ public class WebMvcGraphQLAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public WebMvcGraphQLHandler graphQLHandler(GraphQL.Builder graphQLBuilder) {
return new WebMvcGraphQLHandler(graphQLBuilder.build(), Collections.emptyList());
public GraphQLHttpHandler graphQLHandler(GraphQL.Builder graphQLBuilder) {
return new GraphQLHttpHandler(graphQLBuilder.build(), Collections.emptyList());
}
@Bean
public RouterFunction<ServerResponse> graphQLQueryEndpoint(
ResourceLoader resourceLoader, WebMvcGraphQLHandler handler, GraphQLProperties properties) {
ResourceLoader resourceLoader, GraphQLHttpHandler handler, GraphQLProperties properties) {
String path = properties.getPath();
Resource resource = resourceLoader.getResource("classpath:graphiql/index.html");
return RouterFunctions.route()
.GET(path, req -> ServerResponse.ok().body(resource))
.POST(path, contentType(MediaType.APPLICATION_JSON).and(accept(MediaType.APPLICATION_JSON)), handler)
.POST(path, contentType(MediaType.APPLICATION_JSON).and(accept(MediaType.APPLICATION_JSON)), handler::handle)
.build();
}

View File

@@ -21,8 +21,6 @@ import java.util.Map;
import graphql.ExecutionInput;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.ResolvableType;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
@@ -39,12 +37,6 @@ import org.springframework.web.util.UriComponentsBuilder;
*/
public class WebInput {
static final ParameterizedTypeReference<Map<String, Object>> MAP_PARAMETERIZED_TYPE_REF =
new ParameterizedTypeReference<Map<String, Object>>() {};
static final ResolvableType MAP_RESOLVABLE_TYPE = ResolvableType.forType(MAP_PARAMETERIZED_TYPE_REF);
private final UriComponents uri;
private final HttpHeaders headers;

View File

@@ -21,14 +21,16 @@ import graphql.ExecutionInput;
import graphql.ExecutionResult;
import reactor.core.publisher.Mono;
import org.springframework.graphql.webmvc.GraphQLHttpHandler;
/**
* Web interceptor for GraphQL queries over HTTP. The interceptor allows
* customization of the {@link ExecutionInput} for the query as well as the
* {@link ExecutionResult} of the query and is supported for both Spring MVC and
* Spring WebFlux.
*
* <p>A list of interceptors may be provided to {@link WebMvcGraphQLHandler} or
* to {@link WebFluxGraphQLHandler}. Interceptors are executed in that provided
* <p>A list of interceptors may be provided to {@link GraphQLHttpHandler} or
* to {@link org.springframework.graphql.webflux.GraphQLHttpHandler}. Interceptors are executed in that provided
* order where each interceptor sees the {@code ExecutionInput} or the
* {@code ExecutionResult} that was customized by the previous interceptor.
*/

View File

@@ -33,14 +33,14 @@ import org.springframework.util.CollectionUtils;
* {@link ExecutionInput} and the {@link ExecutionResult} of {@link GraphQL}
* query execution.
*/
class WebInterceptorExecutionChain {
public class WebInterceptorExecutionChain {
private final GraphQL graphQL;
private final List<WebInterceptor> interceptors;
WebInterceptorExecutionChain(GraphQL graphQL, List<WebInterceptor> interceptors) {
public WebInterceptorExecutionChain(GraphQL graphQL, List<WebInterceptor> interceptors) {
Assert.notNull(graphQL, "GraphQL is required");
this.graphQL = graphQL;
this.interceptors = (!CollectionUtils.isEmpty(interceptors) ?

View File

@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.graphql;
package org.springframework.graphql.webflux;
import java.util.List;
import java.util.Map;
@@ -23,15 +23,22 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Mono;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.graphql.WebInput;
import org.springframework.graphql.WebInterceptor;
import org.springframework.graphql.WebInterceptorExecutionChain;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
/**
* WebFlux.fn Handler for GraphQL over HTTP requests.
*/
public class WebFluxGraphQLHandler {
public class GraphQLHttpHandler {
private static final Log logger = LogFactory.getLog(WebFluxGraphQLHandler.class);
private static final Log logger = LogFactory.getLog(GraphQLHttpHandler.class);
private static final ParameterizedTypeReference<Map<String, Object>> MAP_PARAMETERIZED_TYPE_REF =
new ParameterizedTypeReference<Map<String, Object>>() {};
private final WebInterceptorExecutionChain executionChain;
@@ -42,7 +49,7 @@ public class WebFluxGraphQLHandler {
* @param graphQL the GraphQL instance to use for query execution
* @param interceptors 0 or more interceptors to customize input and output
*/
public WebFluxGraphQLHandler(GraphQL graphQL, List<WebInterceptor> interceptors) {
public GraphQLHttpHandler(GraphQL graphQL, List<WebInterceptor> interceptors) {
this.executionChain = new WebInterceptorExecutionChain(graphQL, interceptors);
}
@@ -51,7 +58,7 @@ public class WebFluxGraphQLHandler {
* Handle GraphQL query requests over HTTP.
*/
public Mono<ServerResponse> handleQuery(ServerRequest request) {
return request.bodyToMono(WebInput.MAP_PARAMETERIZED_TYPE_REF)
return request.bodyToMono(MAP_PARAMETERIZED_TYPE_REF)
.flatMap(body -> {
WebInput webInput = new WebInput(request.uri(), request.headers().asHttpHeaders(), body);
if (logger.isDebugEnabled()) {

View File

@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.graphql;
package org.springframework.graphql.webflux;
import java.time.Duration;
import java.util.Collections;
@@ -34,10 +34,16 @@ import org.reactivestreams.Subscription;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.ResolvableType;
import org.springframework.core.codec.Decoder;
import org.springframework.core.codec.Encoder;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.graphql.WebInterceptor;
import org.springframework.graphql.WebInterceptorExecutionChain;
import org.springframework.graphql.WebOutput;
import org.springframework.graphql.WebSocketInput;
import org.springframework.http.MediaType;
import org.springframework.http.codec.DecoderHttpMessageReader;
import org.springframework.http.codec.EncoderHttpMessageWriter;
@@ -56,12 +62,15 @@ import org.springframework.web.reactive.socket.WebSocketSession;
* WebSocketHandler for GraphQL based on
* <a href="https://github.com/enisdenjo/graphql-ws/blob/master/PROTOCOL.md">GraphQL Over WebSocket Protocol</a>
*/
public class WebFluxGraphQLWebSocketHandler implements WebSocketHandler {
public class GraphQLWebSocketHandler implements WebSocketHandler {
private static final Log logger = LogFactory.getLog(WebFluxGraphQLWebSocketHandler.class);
private static final Log logger = LogFactory.getLog(GraphQLWebSocketHandler.class);
private static final List<String> SUB_PROTOCOL_LIST = Collections.singletonList("graphql-transport-ws");
static final ResolvableType MAP_RESOLVABLE_TYPE =
ResolvableType.forType(new ParameterizedTypeReference<Map<String, Object>>() {});
private final WebInterceptorExecutionChain executionChain;
@@ -87,7 +96,7 @@ public class WebFluxGraphQLWebSocketHandler implements WebSocketHandler {
* @param initTimeoutDuration the time within which the
* {@code CONNECTION_INIT} type message must be received.
*/
public WebFluxGraphQLWebSocketHandler(GraphQL graphQL, List<WebInterceptor> interceptors,
public GraphQLWebSocketHandler(GraphQL graphQL, List<WebInterceptor> interceptors,
ServerCodecConfigurer configurer, Duration initTimeoutDuration) {
this.executionChain = new WebInterceptorExecutionChain(graphQL, interceptors);
@@ -98,7 +107,7 @@ public class WebFluxGraphQLWebSocketHandler implements WebSocketHandler {
private static Decoder<?> initDecoder(ServerCodecConfigurer configurer) {
return configurer.getReaders().stream()
.filter(reader -> reader.canRead(WebInput.MAP_RESOLVABLE_TYPE, MediaType.APPLICATION_JSON))
.filter(reader -> reader.canRead(MAP_RESOLVABLE_TYPE, MediaType.APPLICATION_JSON))
.map(reader -> ((DecoderHttpMessageReader<?>) reader).getDecoder())
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No JSON Decoder"));
@@ -106,7 +115,7 @@ public class WebFluxGraphQLWebSocketHandler implements WebSocketHandler {
private static Encoder<?> initEncoder(ServerCodecConfigurer configurer) {
return configurer.getWriters().stream()
.filter(writer -> writer.canWrite(WebInput.MAP_RESOLVABLE_TYPE, MediaType.APPLICATION_JSON))
.filter(writer -> writer.canWrite(MAP_RESOLVABLE_TYPE, MediaType.APPLICATION_JSON))
.map(writer -> ((EncoderHttpMessageWriter<?>) writer).getEncoder())
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No JSON Encoder"));
@@ -162,10 +171,10 @@ public class WebFluxGraphQLWebSocketHandler implements WebSocketHandler {
return session.send(responseFlux);
}
@SuppressWarnings({"unchecked", "ConstantConditions"})
@SuppressWarnings("unchecked")
private Map<String, Object> decode(WebSocketMessage message) {
DataBuffer buffer = DataBufferUtils.retain(message.getPayload());
return (Map<String, Object>) decoder.decode(buffer, WebInput.MAP_RESOLVABLE_TYPE, null, null);
return (Map<String, Object>) decoder.decode(buffer, MAP_RESOLVABLE_TYPE, null, null);
}
@SuppressWarnings("unchecked")
@@ -234,7 +243,7 @@ public class WebFluxGraphQLWebSocketHandler implements WebSocketHandler {
}
DataBuffer buffer = ((Encoder<T>) encoder).encodeValue(
(T) payloadMap, session.bufferFactory(), WebInput.MAP_RESOLVABLE_TYPE,
(T) payloadMap, session.bufferFactory(), MAP_RESOLVABLE_TYPE,
MimeTypeUtils.APPLICATION_JSON, null);
return new WebSocketMessage(WebSocketMessage.Type.TEXT, buffer);

View File

@@ -0,0 +1,21 @@
/*
* Copyright 2020-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@NonNullApi
@NonNullFields
package org.springframework.graphql.webflux;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;

View File

@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.graphql;
package org.springframework.graphql.webmvc;
import java.io.IOException;
import java.util.List;
@@ -26,9 +26,12 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Mono;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.graphql.WebInput;
import org.springframework.graphql.WebInterceptor;
import org.springframework.graphql.WebInterceptorExecutionChain;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.server.ServerWebInputException;
import org.springframework.web.servlet.function.HandlerFunction;
import org.springframework.web.servlet.function.ServerRequest;
import org.springframework.web.servlet.function.ServerResponse;
@@ -36,9 +39,12 @@ import org.springframework.web.servlet.function.ServerResponse;
* GraphQL handler to expose as a WebMvc.fn endpoint via
* {@link org.springframework.web.servlet.function.RouterFunctions}.
*/
public class WebMvcGraphQLHandler implements HandlerFunction<ServerResponse> {
public class GraphQLHttpHandler {
private static Log logger = LogFactory.getLog(WebMvcGraphQLHandler.class);
private final static Log logger = LogFactory.getLog(GraphQLHttpHandler.class);
private static final ParameterizedTypeReference<Map<String, Object>> MAP_PARAMETERIZED_TYPE_REF =
new ParameterizedTypeReference<Map<String, Object>>() {};
private final WebInterceptorExecutionChain executionChain;
@@ -51,7 +57,7 @@ public class WebMvcGraphQLHandler implements HandlerFunction<ServerResponse> {
* @param graphQL the GraphQL instance to use for query execution
* @param interceptors 0 or more interceptors to customize input and output
*/
public WebMvcGraphQLHandler(GraphQL graphQL, List<WebInterceptor> interceptors) {
public GraphQLHttpHandler(GraphQL graphQL, List<WebInterceptor> interceptors) {
this.executionChain = new WebInterceptorExecutionChain(graphQL, interceptors);
}
@@ -83,7 +89,7 @@ public class WebMvcGraphQLHandler implements HandlerFunction<ServerResponse> {
private static Map<String, Object> readBody(ServerRequest request) throws ServletException {
try {
return request.body(WebInput.MAP_PARAMETERIZED_TYPE_REF);
return request.body(MAP_PARAMETERIZED_TYPE_REF);
}
catch (IOException ex) {
throw new ServerWebInputException("I/O error while reading request body", null, ex);

View File

@@ -0,0 +1,21 @@
/*
* Copyright 2020-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@NonNullApi
@NonNullFields
package org.springframework.graphql.webmvc;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;

View File

@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.graphql;
package org.springframework.graphql.webflux;
import java.io.File;
import java.net.URI;
@@ -41,6 +41,10 @@ import reactor.test.StepVerifier;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.graphql.GraphQLDataFetchers;
import org.springframework.graphql.WebInterceptor;
import org.springframework.graphql.WebOutput;
import org.springframework.graphql.webflux.GraphQLWebSocketHandler;
import org.springframework.http.HttpHeaders;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.http.codec.json.Jackson2JsonDecoder;
@@ -57,9 +61,9 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.InstanceOfAssertFactories.map;
/**
* Unit tests for {@link WebFluxGraphQLWebSocketHandler}.
* Unit tests for {@link GraphQLWebSocketHandler}.
*/
public class WebFluxGraphQLWebSocketHandlerTests {
public class GraphQLWebSocketHandlerTests {
private static final Jackson2JsonDecoder decoder = new Jackson2JsonDecoder();
@@ -249,15 +253,15 @@ public class WebFluxGraphQLWebSocketHandlerTests {
.verifyTimeout(Duration.ofMillis(500));
}
private WebFluxGraphQLWebSocketHandler initWebSocketHandler() throws Exception {
private GraphQLWebSocketHandler initWebSocketHandler() throws Exception {
return initWebSocketHandler(Collections.emptyList(), Duration.ofSeconds(69));
}
private WebFluxGraphQLWebSocketHandler initWebSocketHandler(
private GraphQLWebSocketHandler initWebSocketHandler(
@Nullable List<WebInterceptor> interceptors, @Nullable Duration initTimeoutDuration) throws Exception {
GraphQL graphQL = initGraphQL();
return new WebFluxGraphQLWebSocketHandler(graphQL,
return new GraphQLWebSocketHandler(graphQL,
(interceptors != null ? interceptors : Collections.emptyList()),
ServerCodecConfigurer.create(),
(initTimeoutDuration != null ? initTimeoutDuration : Duration.ofSeconds(60)));
@@ -285,7 +289,7 @@ public class WebFluxGraphQLWebSocketHandlerTests {
private Map<String, Object> decode(WebSocketMessage message) {
return (Map<String, Object>) decoder.decode(
DataBufferUtils.retain(message.getPayload()),
WebInput.MAP_RESOLVABLE_TYPE, null, Collections.emptyMap());
GraphQLWebSocketHandler.MAP_RESOLVABLE_TYPE, null, Collections.emptyMap());
}
private void assertMessageType(WebSocketMessage message, String messageType) {