-
-
Notifications
You must be signed in to change notification settings - Fork 722
/
NodeFieldTypeInterceptor.cs
206 lines (178 loc) · 7.56 KB
/
NodeFieldTypeInterceptor.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#nullable enable
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using HotChocolate.Configuration;
using HotChocolate.Execution;
using HotChocolate.Language;
using HotChocolate.Properties;
using HotChocolate.Resolvers;
using HotChocolate.Resolvers.Expressions;
using HotChocolate.Types.Descriptors;
using HotChocolate.Types.Descriptors.Definitions;
using HotChocolate.Types.Introspection;
using Microsoft.Extensions.DependencyInjection;
using static HotChocolate.Properties.TypeResources;
using static HotChocolate.Types.WellKnownContextData;
namespace HotChocolate.Types.Relay;
internal sealed class NodeFieldTypeInterceptor : TypeInterceptor
{
private static readonly Task<object?> _nullTask = Task.FromResult<object?>(null);
private static NameString Node => "node";
private static NameString Nodes => "nodes";
private static NameString Id => "id";
private static NameString Ids => "ids";
public override void OnBeforeCompleteType(
ITypeCompletionContext completionContext,
DefinitionBase? definition,
IDictionary<string, object?> contextData)
{
if ((completionContext.IsQueryType ?? false) &&
definition is ObjectTypeDefinition objectTypeDefinition)
{
ITypeInspector typeInspector = completionContext.TypeInspector;
IIdSerializer serializer =
completionContext.Services.GetService<IIdSerializer>() ??
new IdSerializer();
ObjectFieldDefinition typeNameField = objectTypeDefinition.Fields.First(
t => t.Name.Equals(IntrospectionFields.TypeName) && t.IsIntrospectionField);
var index = objectTypeDefinition.Fields.IndexOf(typeNameField);
CreateNodeField(typeInspector, serializer, objectTypeDefinition.Fields, index + 1);
CreateNodesField(serializer, objectTypeDefinition.Fields, index + 2);
}
}
private static void CreateNodeField(
ITypeInspector typeInspector,
IIdSerializer serializer,
IList<ObjectFieldDefinition> fields,
int index)
{
ExtendedTypeReference node = typeInspector.GetTypeRef(typeof(NodeType));
ExtendedTypeReference id = typeInspector.GetTypeRef(typeof(NonNullType<IdType>));
var field = new ObjectFieldDefinition(
Node,
Relay_NodeField_Description,
node,
ResolveNodeAsync) { Arguments = { new(Id, Relay_NodeField_Id_Description, id) } };
fields.Insert(index, field);
ValueTask<object?> ResolveNodeAsync(IResolverContext ctx)
=> ResolveSingleNode(ctx, serializer, Id);
}
private static void CreateNodesField(
IIdSerializer serializer,
IList<ObjectFieldDefinition> fields,
int index)
{
SyntaxTypeReference nodes = TypeReference.Parse("[Node]!");
SyntaxTypeReference ids = TypeReference.Parse("[ID!]!");
var field = new ObjectFieldDefinition(
Nodes,
Relay_NodesField_Description,
nodes,
ResolveNodeAsync) { Arguments = { new(Ids, Relay_NodesField_Ids_Description, ids) } };
fields.Insert(index, field);
ValueTask<object?> ResolveNodeAsync(IResolverContext ctx)
=> ResolveManyNode(ctx, serializer);
}
private static async ValueTask<object?> ResolveSingleNode(
IResolverContext context,
IIdSerializer serializer,
NameString argumentName)
{
StringValueNode nodeId = context.ArgumentLiteral<StringValueNode>(argumentName);
IdValue deserializedId = serializer.Deserialize(nodeId.Value);
NameString typeName = deserializedId.TypeName;
context.SetLocalState(NodeId, nodeId.Value);
context.SetLocalState(InternalId, deserializedId.Value);
context.SetLocalState(InternalType, typeName);
context.SetLocalState(WellKnownContextData.IdValue, deserializedId);
if (context.Schema.TryGetType<ObjectType>(typeName, out ObjectType? type) &&
type.ContextData.TryGetValue(NodeResolver, out var o) &&
o is FieldResolverDelegate resolver)
{
return await resolver.Invoke(context).ConfigureAwait(false);
}
return null;
}
private static async ValueTask<object?> ResolveManyNode(
IResolverContext context,
IIdSerializer serializer)
{
if (context.ArgumentKind(Ids) == ValueKind.List)
{
ListValueNode list = context.ArgumentLiteral<ListValueNode>(Ids);
Task<object?>[] tasks = ArrayPool<Task<object?>>.Shared.Rent(list.Items.Count);
tasks.AsSpan().Slice(0, list.Items.Count).Clear();
var result = new object?[list.Items.Count];
try
{
for (var i = 0; i < list.Items.Count; i++)
{
context.RequestAborted.ThrowIfCancellationRequested();
// it is guaranteed that this is always a string literal.
StringValueNode nodeId = (StringValueNode)list.Items[i];
IdValue deserializedId = serializer.Deserialize(nodeId.Value);
NameString typeName = deserializedId.TypeName;
context.SetLocalState(NodeId, nodeId.Value);
context.SetLocalState(InternalId, deserializedId.Value);
context.SetLocalState(InternalType, typeName);
context.SetLocalState(WellKnownContextData.IdValue, deserializedId);
tasks[i] =
context.Schema.TryGetType<ObjectType>(typeName, out ObjectType? type) &&
type.ContextData.TryGetValue(NodeResolver, out var o) &&
o is FieldResolverDelegate resolver
? resolver.Invoke(new ResolverContextProxy(context)).AsTask()
: _nullTask;
}
for (var i = 0; i < list.Items.Count; i++)
{
context.RequestAborted.ThrowIfCancellationRequested();
Task<object?> task = tasks[i];
if (task.IsCompleted)
{
if (task.Exception is null)
{
result[i] = task.Result;
}
else
{
result[i] = null;
ReportError(context, i, task.Exception);
}
}
else
{
try
{
result[i] = await task;
}
catch (Exception ex)
{
result[i] = null;
ReportError(context, i, ex);
}
}
}
return result;
}
finally
{
ArrayPool<Task<object?>>.Shared.Return(tasks);
}
}
else
{
var result = new object?[1];
result[0] = await ResolveSingleNode(context, serializer, Ids);
return result;
}
}
private static void ReportError(IResolverContext context, int item, Exception ex)
{
Path itemPath = PathFactory.Instance.Append(context.Path, item);
context.ReportError(ex, error => error.SetPath(itemPath));
}
}