Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add persisted document support #71

Merged
merged 1 commit into from
Aug 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project>

<PropertyGroup>
<VersionPrefix>6.0.0-preview</VersionPrefix>
<VersionPrefix>6.0.1-preview</VersionPrefix>
<LangVersion>12.0</LangVersion>
<Copyright>Shane Krueger</Copyright>
<Authors>Shane Krueger</Authors>
Expand All @@ -20,7 +20,7 @@
<ImplicitUsings>true</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<GraphQLVersion>8.0.0</GraphQLVersion>
<GraphQLVersion>8.0.1</GraphQLVersion>
<NoWarn>$(NoWarn);IDE0056;IDE0057;NU1902;NU1903</NoWarn>
</PropertyGroup>

Expand Down
11 changes: 8 additions & 3 deletions src/GraphQL.AspNetCore3/GraphQLHttpMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ public class GraphQLHttpMiddleware : IUserContextBuilder
private const string VARIABLES_KEY = "variables";
private const string EXTENSIONS_KEY = "extensions";
private const string OPERATION_NAME_KEY = "operationName";
private const string DOCUMENT_ID_KEY = "documentId";
private const string OPERATIONS_KEY = "operations"; // used for multipart/form-data requests per https://github.com/jaydenseric/graphql-multipart-request-spec
private const string MAP_KEY = "map"; // used for multipart/form-data requests per https://github.com/jaydenseric/graphql-multipart-request-spec
private const string MEDIATYPE_GRAPHQLJSON = "application/graphql+json";
Expand Down Expand Up @@ -174,7 +175,8 @@ public virtual async Task InvokeAsync(HttpContext context)
Query = urlGQLRequest?.Query ?? bodyGQLRequest?.Query,
Variables = urlGQLRequest?.Variables ?? bodyGQLRequest?.Variables,
Extensions = urlGQLRequest?.Extensions ?? bodyGQLRequest?.Extensions,
OperationName = urlGQLRequest?.OperationName ?? bodyGQLRequest?.OperationName
OperationName = urlGQLRequest?.OperationName ?? bodyGQLRequest?.OperationName,
DocumentId = urlGQLRequest?.DocumentId ?? bodyGQLRequest?.DocumentId,
};

await HandleRequestAsync(context, _next, gqlRequest);
Expand Down Expand Up @@ -299,8 +301,8 @@ void ApplyMapToRequests(Dictionary<string, string?[]> map, IFormCollection form,

foreach (var entry in map) {
// validate entry key
if (entry.Key == "" || entry.Key == "query" || entry.Key == "operationName" || entry.Key == "variables" || entry.Key == "extensions" || entry.Key == "operations" || entry.Key == "map")
throw new InvalidMapError("Map key cannot be query, operationName, variables, extensions, operations or map.");
if (entry.Key == "" || entry.Key == QUERY_KEY || entry.Key == OPERATION_NAME_KEY || entry.Key == VARIABLES_KEY || entry.Key == EXTENSIONS_KEY || entry.Key == DOCUMENT_ID_KEY || entry.Key == OPERATIONS_KEY || entry.Key == MAP_KEY)
throw new InvalidMapError("Map key cannot be query, operationName, variables, extensions, documentId, operations or map.");
// locate file
var file = form.Files[entry.Key]
?? throw new InvalidMapError("Map key does not refer to an uploaded file.");
Expand Down Expand Up @@ -603,6 +605,7 @@ protected virtual async Task<ExecutionResult> ExecuteRequestAsync(HttpContext co
Query = request?.Query,
Variables = request?.Variables,
Extensions = request?.Extensions,
DocumentId = request?.DocumentId,
CancellationToken = context.RequestAborted,
OperationName = request?.OperationName,
RequestServices = serviceProvider,
Expand Down Expand Up @@ -884,13 +887,15 @@ protected virtual Task WriteErrorResponseAsync(HttpContext context, HttpStatusCo
Variables = _options.ReadVariablesFromQueryString && queryCollection.TryGetValue(VARIABLES_KEY, out var variablesValues) ? _serializer.Deserialize<Inputs>(variablesValues[0]) : null,
Extensions = _options.ReadExtensionsFromQueryString && queryCollection.TryGetValue(EXTENSIONS_KEY, out var extensionsValues) ? _serializer.Deserialize<Inputs>(extensionsValues[0]) : null,
OperationName = queryCollection.TryGetValue(OPERATION_NAME_KEY, out var operationNameValues) ? operationNameValues[0] : null,
DocumentId = queryCollection.TryGetValue(DOCUMENT_ID_KEY, out var documentIdValues) ? documentIdValues[0] : null,
};

private GraphQLRequest DeserializeFromFormBody(IFormCollection formCollection) => new() {
Query = formCollection.TryGetValue(QUERY_KEY, out var queryValues) ? queryValues[0] : null,
Variables = formCollection.TryGetValue(VARIABLES_KEY, out var variablesValues) ? _serializer.Deserialize<Inputs>(variablesValues[0]) : null,
Extensions = formCollection.TryGetValue(EXTENSIONS_KEY, out var extensionsValues) ? _serializer.Deserialize<Inputs>(extensionsValues[0]) : null,
OperationName = formCollection.TryGetValue(OPERATION_NAME_KEY, out var operationNameValues) ? operationNameValues[0] : null,
DocumentId = formCollection.TryGetValue(DOCUMENT_ID_KEY, out var documentIdValues) ? documentIdValues[0] : null,
};

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ protected override async Task<ExecutionResult> ExecuteRequestAsync(OperationMess
Query = request.Query,
Variables = request.Variables,
Extensions = request.Extensions,
DocumentId = request.DocumentId,
OperationName = request.OperationName,
RequestServices = scope.ServiceProvider,
CancellationToken = CancellationToken,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ protected override async Task<ExecutionResult> ExecuteRequestAsync(OperationMess
Query = request.Query,
Variables = request.Variables,
Extensions = request.Extensions,
DocumentId = request.DocumentId,
OperationName = request.OperationName,
RequestServices = scope.ServiceProvider,
CancellationToken = CancellationToken,
Expand Down
55 changes: 44 additions & 11 deletions src/Tests/Middleware/GetTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Net;
using GraphQL.PersistedDocuments;

namespace Tests.Middleware;

Expand All @@ -7,20 +8,39 @@ public class GetTests : IDisposable
private GraphQLHttpMiddlewareOptions _options = null!;
private GraphQLHttpMiddlewareOptions _options2 = null!;
private readonly Action<ExecutionOptions> _configureExecution = _ => { };
private bool _enablePersistedDocuments = true;
private readonly TestServer _server;

public GetTests()
{
var hostBuilder = new WebHostBuilder();
hostBuilder.ConfigureServices(services => {
services.AddSingleton<Chat.Services.ChatService>();
services.AddGraphQL(b => b
.AddAutoSchema<Chat.Schema.Query>(s => s
.WithMutation<Chat.Schema.Mutation>()
.WithSubscription<Chat.Schema.Subscription>())
.AddSchema<Schema2>()
.AddSystemTextJson()
.ConfigureExecutionOptions(o => _configureExecution(o)));
services.AddGraphQL(b => {
b
.AddAutoSchema<Chat.Schema.Query>(s => s
.WithMutation<Chat.Schema.Mutation>()
.WithSubscription<Chat.Schema.Subscription>())
.AddSchema<Schema2>()
.AddSystemTextJson()
.ConfigureExecution((options, next) => {
if (_enablePersistedDocuments) {
var handler = options.RequestServices!.GetRequiredService<PersistedDocumentHandler>();
return handler.ExecuteAsync(options, next);
}
return next(options);
})
.ConfigureExecutionOptions(o => _configureExecution(o));
b.Services.Configure<PersistedDocumentOptions>(o => {
o.AllowOnlyPersistedDocuments = false;
o.AllowedPrefixes.Add("test");
o.GetQueryDelegate = (options, prefix, payload) =>
prefix == "test" && payload == "abc" ? new("{count}") :
prefix == "test" && payload == "form" ? new("query op1{ext} query op2($test:String!){ext var(test:$test)}") :
default;
});
});
services.AddSingleton<PersistedDocumentHandler>();
#if NETCOREAPP2_1 || NET48
services.AddHostApplicationLifetime();
#endif
Expand Down Expand Up @@ -63,6 +83,14 @@ public async Task BasicTest()
await response.ShouldBeAsync(@"{""data"":{""count"":0}}");
}

[Fact]
public async Task PersistedDocumentTest()
{
var client = _server.CreateClient();
using var response = await client.GetAsync("/graphql?documentId=test:abc");
await response.ShouldBeAsync("""{"data":{"count":0}}""");
}

[Theory]
[InlineData(true, true)]
[InlineData(true, false)]
Expand Down Expand Up @@ -160,14 +188,19 @@ public async Task QueryParseError(bool badRequest)
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task NoQuery(bool badRequest)
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(true, true)]
public async Task NoQuery(bool badRequest, bool usePersistedDocumentHandler)
{
_enablePersistedDocuments = usePersistedDocumentHandler;
_options.ValidationErrorsReturnBadRequest = badRequest;
var client = _server.CreateClient();
using var response = await client.GetAsync("/graphql");
await response.ShouldBeAsync(badRequest, @"{""errors"":[{""message"":""GraphQL query is missing."",""extensions"":{""code"":""QUERY_MISSING"",""codes"":[""QUERY_MISSING""]}}]}");
await response.ShouldBeAsync(badRequest, usePersistedDocumentHandler
? """{"errors":[{"message":"The request must have a documentId parameter.","extensions":{"code":"DOCUMENT_ID_MISSING","codes":["DOCUMENT_ID_MISSING"]}}]}"""
: """{"errors":[{"message":"GraphQL query is missing.","extensions":{"code":"QUERY_MISSING","codes":["QUERY_MISSING"]}}]}""");
}

[Theory]
Expand Down
Loading
Loading