forked from SimonCropp/GraphQL.EntityFramework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraphQlController.cs
89 lines (80 loc) · 2.12 KB
/
GraphQlController.cs
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Threading;
using System.Threading.Tasks;
using GraphQL;
using GraphQL.Types;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Newtonsoft.Json.Linq;
#region GraphQlController
[Route("[controller]")]
[ApiController]
public class GraphQlController :
Controller
{
IDocumentExecuter executer;
ISchema schema;
public GraphQlController(ISchema schema, IDocumentExecuter executer)
{
this.schema = schema;
this.executer = executer;
}
[HttpPost]
public Task<ExecutionResult> Post(
[BindRequired, FromBody] PostBody body,
CancellationToken cancellation)
{
return Execute(body.Query, body.OperationName, body.Variables, cancellation);
}
public class PostBody
{
public string? OperationName;
public string Query = null!;
public JObject? Variables;
}
[HttpGet]
public Task<ExecutionResult> Get(
[FromQuery] string query,
[FromQuery] string? variables,
[FromQuery] string? operationName,
CancellationToken cancellation)
{
var jObject = ParseVariables(variables);
return Execute(query, operationName, jObject, cancellation);
}
Task<ExecutionResult> Execute(string query,
string? operationName,
JObject? variables,
CancellationToken cancellation)
{
var options = new ExecutionOptions
{
Schema = schema,
Query = query,
OperationName = operationName,
Inputs = variables?.ToInputs(),
CancellationToken = cancellation,
#if (DEBUG)
ExposeExceptions = true,
EnableMetrics = true,
#endif
};
return executer.ExecuteAsync(options);
}
static JObject? ParseVariables(string? variables)
{
if (variables == null)
{
return null;
}
try
{
return JObject.Parse(variables);
}
catch (Exception exception)
{
throw new Exception("Could not parse variables.", exception);
}
}
}
#endregion