Add protected encode method to WebFlux AbstractGraphQlHttpHandler

This helps to encode directly when needed, e.g. for multipart
stream with incremental delivery.

See gh-959
This commit is contained in:
rstoyanchev
2024-04-26 12:00:37 +01:00
parent f61dfc56fe
commit 1ea64dca5c
2 changed files with 19 additions and 8 deletions

View File

@@ -18,6 +18,7 @@ package org.springframework.graphql.server.webflux;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -131,13 +132,24 @@ public abstract class AbstractGraphQlHttpHandler {
protected abstract Mono<ServerResponse> prepareResponse(ServerRequest request, WebGraphQlResponse response);
/**
* Encode the GraphQL response if custom codecs were provided, or otherwise
* return the result map.
* Encode the GraphQL response if custom codecs were provided, or return the result map.
* @param response the GraphQL response
* @return the encoded response or the result map
*/
protected Object encodeResponseIfNecessary(WebGraphQlResponse response) {
return (this.codecDelegate != null) ? this.codecDelegate.encode(response) : response.toMap();
Map<String, Object> resultMap = response.toMap();
return (this.codecDelegate != null) ? encode(resultMap) : resultMap;
}
/**
* Encode the result map.
* <p>This method assumes that a {@link CodecConfigurer} has been provided.
* @param resultMap the result to encode
* @return the encoded result map
*/
protected DataBuffer encode(Map<String, Object> resultMap) {
Assert.state(this.codecDelegate != null, "CodecConfigurer was not provided");
return this.codecDelegate.encode(resultMap);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2024 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.
@@ -26,7 +26,6 @@ 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.DefaultDataBufferFactory;
import org.springframework.graphql.GraphQlResponse;
import org.springframework.graphql.server.support.SerializableGraphQlRequest;
import org.springframework.http.MediaType;
import org.springframework.http.codec.CodecConfigurer;
@@ -77,9 +76,9 @@ final class HttpCodecDelegate {
@SuppressWarnings("unchecked")
DataBuffer encode(GraphQlResponse response) {
return ((Encoder<Map<String, Object>>) this.encoder)
.encodeValue(response.toMap(), DefaultDataBufferFactory.sharedInstance, RESPONSE_TYPE, MimeTypeUtils.APPLICATION_JSON, null);
DataBuffer encode(Map<String, Object> resultMap) {
return ((Encoder<Map<String, Object>>) this.encoder).encodeValue(
resultMap, DefaultDataBufferFactory.sharedInstance, RESPONSE_TYPE, MimeTypeUtils.APPLICATION_JSON, null);
}
@SuppressWarnings("unchecked")