Repository navigation
Expand file tree
/
Copy pathField.cs
More file actions
388 lines (352 loc) · 17.6 KB
/
Copy pathField.cs
File metadata and controls
388 lines (352 loc) · 17.6 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
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using EntityGraphQL.Compiler;
using EntityGraphQL.Compiler.Util;
using EntityGraphQL.Extensions;
using EntityGraphQL.Schema.FieldExtensions;
namespace EntityGraphQL.Schema;
/// <summary>
/// Describes an entity field. It's expression based on the base type (your data model) and it's mapped return type
/// </summary>
public class Field : BaseField
{
public override GraphQLQueryFieldType FieldType { get; } = GraphQLQueryFieldType.Query;
public IEnumerable<string> RequiredArgumentNames
{
get
{
if (Arguments == null)
return new List<string>();
var required = Arguments.Where(f => f.Value.Type.TypeDotnet.IsConstructedGenericType && f.Value.Type.TypeDotnet.GetGenericTypeDefinition() == typeof(RequiredField<>)).Select(f => f.Key);
return required.ToList();
}
}
/// <summary>
/// Set a service-backed resolve on a field constructed without one. Used to build fields programmatically
/// (e.g. aggregate leaves that reduce a collection using a service). <paramref name="services"/> are the
/// free service parameters in the resolve body. When <paramref name="extractedFields"/> is supplied it is
/// used verbatim as the service dependencies (the default extractor mis-handles a reduction over the
/// context, so callers that build a reduction provide the deps projection explicitly).
/// </summary>
internal void SetServiceResolve(LambdaExpression resolve, IEnumerable<ParameterExpression> services, List<GraphQLExtractedField>? extractedFields = null, IBulkFieldResolver? aggregateBulkResolver = null)
{
Services.AddRange(services);
ProcessResolveExpression(resolve, extractedFields == null, false);
if (extractedFields != null)
ExtractedFieldsFromServices = extractedFields;
// NOTE: deliberately NOT set as BulkResolver — that would make the normal bulk loader machinery try to
// resolve it. The aggregate reduces the bulk dictionary itself in pass 2 (see GraphQLScalarField).
AggregateBulkResolver = aggregateBulkResolver;
IsAggregateReductionLeaf = true;
}
/// <summary>
/// Set the resolve from an expression returned by a [GraphQLField] expression-factory member at schema
/// build time. Routes through the same SetUpField path as AddField().Resolve() so the expression fully
/// composes into the database-bound pass (or gets standard service two-pass handling when the expression
/// declares service parameters after the context parameter).
/// </summary>
internal void SetExpressionResolve(LambdaExpression resolve, List<ParameterExpression> services)
{
Services.AddRange(services);
SetUpField(resolve, services.Count > 0, false, false);
}
/// <summary>
/// True when this field is an aggregate leaf built by <see cref="Schema.FieldExtensions.AggregateExtension"/>
/// that reduces a collection using a service. Gates the nested reduction two-pass handling in
/// <see cref="Compiler.GraphQLScalarField"/> so it never hijacks an ordinary service field that happens to
/// reduce a sub-collection (e.g. <c>p => p.Tasks.Sum(t => svc.Score(t.Id))</c>).
/// </summary>
internal bool IsAggregateReductionLeaf { get; private set; }
/// <summary>
/// The bulk resolver of the element field this aggregate leaf reduces, when aggregating a bulk-resolved field.
/// Used by <see cref="Compiler.GraphQLScalarField"/> to fetch all values in one call and reduce in memory.
/// </summary>
internal IBulkFieldResolver? AggregateBulkResolver { get; private set; }
protected void ProcessResolveExpression(LambdaExpression resolve, bool withServices, bool hasArguments)
{
ResolveExpression = resolve.Body;
FieldParam = resolve.Parameters.First();
if (hasArguments)
ArgumentsParameter = resolve.Parameters.ElementAt(1);
if (resolve.Body.NodeType == ExpressionType.MemberAccess)
{
var memberExp = (MemberExpression)resolve.Body;
ReturnType.TypeNotNullable = GraphQLNotNullAttribute.IsMemberMarkedNotNull(memberExp.Member) || ReturnType.TypeNotNullable;
ReturnType.ElementTypeNullable = GraphQLElementTypeNullableAttribute.IsMemberElementMarkedNullable(memberExp.Member) || ReturnType.ElementTypeNullable;
}
if (withServices)
{
var extractor = new ExpressionExtractor();
ExtractedFieldsFromServices = extractor.Extract(ResolveExpression, FieldParam, false)?.Select(i => new GraphQLExtractedField(Schema, i.Key, i.Value, FieldParam)).ToList();
}
}
/// <summary>
/// Create a GraphQL field
/// </summary>
/// <param name="schema">Schema it belongs to</param>
/// <param name="fromType">Schema type the field belongs to</param>
/// <param name="name">Name of the field</param>
/// <param name="resolve">Expression for executing the field</param>
/// <param name="description">Description of the field</param>
/// <param name="fieldArgsObject">
/// You may supply an object containing the argument
/// definitions. This is useful for the anonymous argument types used when building fields
/// </param>
/// <param name="returnType">Schema return type of the field</param>
/// <param name="requiredAuth">Any authorization require to query the field</param>
public Field(
ISchemaProvider schema,
ISchemaType fromType,
string name,
LambdaExpression? resolve,
string? description,
object? fieldArgsObject,
GqlTypeInfo returnType,
RequiredAuthorization? requiredAuth
)
: base(schema, fromType, name, description, returnType)
{
RequiredAuthorization = requiredAuth;
Extensions = [];
if (resolve != null)
{
ProcessResolveExpression(resolve, false, fieldArgsObject != null);
}
if (fieldArgsObject != null)
{
Arguments = ExpressionUtil.ObjectToDictionaryArgs(schema, fieldArgsObject);
ExpressionArgumentType = fieldArgsObject.GetType();
}
}
/// <summary>
/// Add the fields a bulk resolver's key selector reads to the fields the per-item resolver already
/// extracts. A bulk resolver builds on a resolver rather than replacing it - the per-item resolver runs
/// whenever the bulk load can not (e.g. the field is selected below another service field), so a field
/// with only a bulk resolver has no way to resolve at all.
/// </summary>
protected void AddBulkResolverKeyFields(IEnumerable<GraphQLExtractedField> fields)
{
if (ExtractedFieldsFromServices == null)
throw new EntityGraphQLSchemaException(
$"Field '{Name}' has a bulk resolver but no resolver to bulk load for. Call Resolve<TService>() (or ResolveAsync<TService>()) before ResolveBulk()/ResolveBulkAsync() - it is used for the field whenever the bulk load can not run."
);
ExtractedFieldsFromServices.AddRange(fields);
}
/// <summary>
/// Create a GraphQL field
/// </summary>
/// <param name="schema">Schema it belongs to</param>
/// <param name="fromType">Schema type the field belongs to</param>
/// <param name="name">Name of the field</param>
/// <param name="resolve">Expression for executing the field</param>
/// <param name="description">Description of the field</param>
/// <param name="fieldArgs">List of arguments for the field</param>
/// <param name="returnType">Schema return type of the field</param>
/// <param name="requiredAuth">Any authorization require to query the field</param>
public Field(
ISchemaProvider schema,
ISchemaType fromType,
string name,
LambdaExpression? resolve,
string? description,
Dictionary<string, ArgType>? fieldArgs,
GqlTypeInfo returnType,
RequiredAuthorization? requiredAuth
)
: base(schema, fromType, name, description, returnType)
{
RequiredAuthorization = requiredAuth;
Extensions = [];
if (resolve != null)
{
ProcessResolveExpression(resolve, false, fieldArgs != null);
}
if (fieldArgs != null)
{
Arguments = fieldArgs;
ExpressionArgumentType = LinqRuntimeTypeBuilder.GetDynamicType(fieldArgs.ToDictionary(x => x.Key, x => x.Value.RawType), name);
}
}
/// <summary>
/// Defines if the return type of this field is nullable or not.
/// </summary>
/// <param name="nullable"></param>
/// <returns></returns>
public new Field IsNullable(bool nullable)
{
ReturnType.TypeNotNullable = !nullable;
return this;
}
/// <summary>
/// Update the return type information for this field
/// </summary>
/// <param name="gqlTypeInfo"></param>
public new Field Returns(GqlTypeInfo gqlTypeInfo)
{
return (Field)base.Returns(gqlTypeInfo);
}
/// <summary>
/// Update the return Type of this field
/// </summary>
/// <param name="schemaTypeName"></param>
/// <returns></returns>
public Field Returns(string schemaTypeName)
{
var gqlTypeInfo = new GqlTypeInfo(() => Schema.Type(schemaTypeName), Schema.Type(schemaTypeName).TypeDotnet);
gqlTypeInfo.IsList = ResolveExpression?.Type.IsEnumerableOrArray() ?? gqlTypeInfo.IsList;
Returns(gqlTypeInfo);
return this;
}
public override (Expression? expression, ParameterExpression? argumentParam) GetExpression(
Expression fieldExpression,
Expression? fieldContext,
BaseGraphQLField? fieldNode,
ParameterExpression? schemaContext,
CompileContext compileContext,
IReadOnlyDictionary<string, object?> args,
ParameterExpression? docParam,
IArgumentsTracker? docVariables,
IEnumerable<GraphQLDirective> directives,
bool contextChanged,
bool withoutServiceFields,
ParameterReplacer replacer
)
{
Expression? expression = fieldExpression;
// extensions are given the field's own expression as Context. Record the context it is bound to below so an
// extension compiling a child field can rebuild from it - see CompileContext.GetFieldContext
if (fieldContext != null && fieldNode != null && !contextChanged && Extensions.Count > 0)
compileContext.SetFieldContext(fieldNode, fieldContext);
// don't store parameterReplacer as a class field as GetExpression is called in compiling - i.e. across threads
(var result, var argumentParam) = PrepareFieldExpression(args, expression!, replacer, expression, fieldNode, docParam, docVariables, contextChanged, withoutServiceFields, compileContext);
if (result == null)
return (null, null);
// the expressions we collect have a different starting parameter. We need to change that
// if (FieldParam != null)
if (FieldParam != null && (!contextChanged || IsAsync))
{
if (fieldContext != null)
result = replacer.Replace(result, FieldParam, fieldContext);
else if (fieldNode?.ParentNode?.NextFieldContext != null && fieldNode?.ParentNode.NextFieldContext.Type != FieldParam.Type)
result = replacer.Replace(result, FieldParam, fieldNode!.ParentNode.NextFieldContext);
}
// need to make sure the schema context param is correct
if (schemaContext != null && !contextChanged)
{
// remaining internal use until the 7.0 refactor threads the actual schema-context ParameterExpression through
#pragma warning disable CS0618
result = replacer.ReplaceByType(result, schemaContext.Type, schemaContext);
#pragma warning restore CS0618
}
return (result, argumentParam);
}
private (Expression? fieldExpression, ParameterExpression? argumentParam) PrepareFieldExpression(
IReadOnlyDictionary<string, object?> args,
Expression fieldExpression,
ParameterReplacer replacer,
Expression context,
BaseGraphQLField? fieldNode,
ParameterExpression? docParam,
IArgumentsTracker? docVariables,
bool servicesPass,
bool withoutServiceFields,
CompileContext compileContext
)
{
object? argumentValue = null;
Expression? result = fieldExpression;
var validationErrors = new HashSet<string>();
var originalArgParam = ArgumentsParameter;
ParameterExpression? newArgParam = null;
if (originalArgParam != null)
{
// create a new argument for execution
newArgParam = Expression.Parameter(originalArgParam.Type, $"{originalArgParam.Name}_exec");
compileContext.AddArgsToCompileContext(this, args, docParam, docVariables, ref argumentValue, validationErrors, newArgParam);
}
if (Extensions.Count > 0)
{
foreach (var extension in Extensions)
{
if (result != null)
{
var extensionContext = new FieldExtensionExpressionContext
{
FieldNode = fieldNode!,
Expression = result!,
ArgumentParameter = newArgParam,
Arguments = argumentValue,
Context = context,
ServicesPass = servicesPass,
WithoutServiceFields = withoutServiceFields,
ParameterReplacer = replacer,
OriginalArgumentParameter = originalArgParam,
CompileContext = compileContext,
};
(result, originalArgParam, newArgParam, argumentValue) = extension.GetExpressionAndArguments(this, extensionContext);
}
}
}
GraphQLHelper.ValidateAndReplaceFieldArgs(this, originalArgParam, replacer, ref argumentValue, ref result!, validationErrors, newArgParam);
return (result, newArgParam);
}
protected void SetUpField(LambdaExpression fieldExpression, bool withServices, bool hasArguments, bool isAsync)
{
ProcessResolveExpression(fieldExpression, withServices, hasArguments);
var returnType = fieldExpression.Body.Type;
// Because we use the return type as object to make the compile time interface nicer we need to get the real return type
if (fieldExpression.Body.NodeType == ExpressionType.Convert)
{
returnType = ((UnaryExpression)fieldExpression.Body).Operand.Type;
ResolveExpression = ((UnaryExpression)ResolveExpression!).Operand;
}
if (fieldExpression.Body.NodeType == ExpressionType.Call)
returnType = ((MethodCallExpression)fieldExpression.Body).Type;
// do the above before unwrapping Task<>
returnType = SchemaBuilder.GetReturnType(returnType, out bool returnsAsync);
if (returnsAsync)
{
IsAsync = true;
// Normalize Task<TCollection> → Task<IEnumerable<T>> in the stored expression so
// all downstream compilation always sees a consistent Task<IEnumerable<T>> type.
// Expression.Call (used in MakeSelectWithDynamicType) resolves generic overloads by
// exact type match, so Task<List<T>>, Task<ICollection<T>> etc. would fail to match
// the SelectWithNullCheck(Task<IEnumerable<T>>, …) overload without this.
// We do it here — once at registration — rather than at every compilation site.
if (ResolveExpression != null)
{
// ValueTask<T> has no Select overloads of its own - hand it on as the Task<T> everything below
// (and the whole compilation pipeline) already handles
if (ResolveExpression.Type.IsGenericType && ResolveExpression.Type.GetGenericTypeDefinition() == typeof(ValueTask<>))
ResolveExpression = Expression.Call(ResolveExpression, ResolveExpression.Type.GetMethod(nameof(ValueTask<object>.AsTask))!);
var exprType = ResolveExpression.Type;
if (exprType.IsGenericType && exprType.GetGenericTypeDefinition() == typeof(Task<>))
{
var taskInner = exprType.GetGenericArguments()[0];
var elementType = returnType.GetEnumerableOrArrayType();
if (elementType != null)
{
var exactEnumType = typeof(IEnumerable<>).MakeGenericType(elementType);
if (
taskInner != exactEnumType
&& taskInner.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>) && i.GetGenericArguments()[0] == elementType)
)
{
ResolveExpression = Expression.Call(typeof(EnumerableExtensions), nameof(EnumerableExtensions.ToEnumerableTask), [taskInner, elementType], ResolveExpression);
}
}
}
}
}
if (!isAsync && IsAsync)
throw new EntityGraphQLSchemaException("Field is synchronous but returns an async type. Use ResolveAsync() or resolve the field expression with .GetAwaiter().GetResult()");
ReturnType = SchemaBuilder.MakeGraphQlType(Schema, false, returnType, null, Name, FromType);
}
public new Field AsService()
{
base.AsService();
return this;
}
}