-
-
Notifications
You must be signed in to change notification settings - Fork 725
/
QueryableSortMiddleware.cs
62 lines (52 loc) · 1.85 KB
/
QueryableSortMiddleware.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HotChocolate.Language;
using HotChocolate.Resolvers;
namespace HotChocolate.Types.Sorting
{
public class QueryableSortMiddleware<T>
{
private readonly SortMiddlewareContext _contextData;
private readonly FieldDelegate _next;
public QueryableSortMiddleware(
FieldDelegate next,
SortMiddlewareContext contextData)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_contextData = contextData
?? throw new ArgumentNullException(nameof(contextData));
}
public async Task InvokeAsync(IMiddlewareContext context)
{
await _next(context).ConfigureAwait(false);
IValueNode sortArgument = context.ArgumentLiteral<IValueNode>(_contextData.ArgumentName);
if (sortArgument is NullValueNode)
{
return;
}
IQueryable<T>? source = null;
if (context.Result is IQueryable<T> q)
{
source = q;
}
else if (context.Result is IEnumerable<T> e)
{
source = e.AsQueryable();
}
if (source is not null &&
context.Field.Arguments[_contextData.ArgumentName].Type is InputObjectType iot &&
iot is ISortInputType { EntityType: not null! } fit)
{
var visitorCtx = new QueryableSortVisitorContext(
iot,
fit.EntityType,
source is EnumerableQuery);
QueryableSortVisitor.Default.Visit(sortArgument, visitorCtx);
source = visitorCtx.Sort(source);
context.Result = source;
}
}
}
}