-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathGraphQlMiddleware.cs
More file actions
75 lines (61 loc) · 1.98 KB
/
Copy pathGraphQlMiddleware.cs
File metadata and controls
75 lines (61 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System.Net;
using GraphQL;
using GraphQL.Attachments;
using GraphQL.SystemTextJson;
using GraphQL.Types;
public class GraphQlMiddleware(ISchema schema, IDocumentExecuter executer) :
IMiddleware
{
static HttpReaderWriter readerWriter = new(new GraphQLSerializer(indent: true));
#region Invoke
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var cancel = context.RequestAborted;
var response = context.Response;
var request = context.Request;
var isGet = HttpMethods.IsGet(request.Method);
var isPost = HttpMethods.IsPost(request.Method);
if (isGet)
{
var (query, inputs, operation) = readerWriter.ReadGet(request);
await Execute(response, query, operation, null, inputs, cancel);
return;
}
if (isPost)
{
var (query, inputs, attachments, operation) = await readerWriter.ReadPost(request, cancel);
await Execute(response, query, operation, attachments, inputs, cancel);
return;
}
response.Headers.Allow = "GET, POST";
response.StatusCode = (int) HttpStatusCode.BadRequest;
}
#endregion
async Task Execute(
HttpResponse response,
string query,
string? operation,
IIncomingAttachments? attachments,
Inputs? inputs,
Cancel cancel)
{
var options = new ExecutionOptions
{
Schema = schema,
Query = query,
OperationName = operation,
Variables = inputs,
CancellationToken = cancel,
#if (DEBUG)
ThrowOnUnhandledException = true,
EnableMetrics = true,
#endif
};
#region ExecuteWithAttachments
var result = await executer.ExecuteWithAttachments(options, attachments);
#endregion
#region ResponseWriter
await readerWriter.WriteResult(response, result, cancel);
#endregion
}
}