-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSchemaHelpers.cs
60 lines (54 loc) · 1.91 KB
/
SchemaHelpers.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
using System;
using System.Linq;
using System.Reflection;
using HotChocolate;
using HotChocolate.Configuration.Bindings;
using HotChocolate.Types;
namespace GraphQLHCSample
{
/*
* These attributes and extensions follow a similar pattern as our RegisterServiceAttribute
* but for GraphQL types so I felt it'd be more natural to register them like this
*/
[AttributeUsage(AttributeTargets.Class)]
public class ComplexTypeAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Class)]
public class ResolverAttribute : Attribute
{
public Type Of { get; private set; }
public ResolverAttribute(Type of)
{
Of = of;
}
}
public static class SchemaBuilderExtensions
{
public static ISchemaBuilder BindTypesFromAttributes(this ISchemaBuilder builder)
{
void AddBindings<T>(Func<Type, IBindingBuilder> builderFunc) where T : Attribute
{
var types = Assembly.GetCallingAssembly()
.GetTypes()
.Where(t => t.GetCustomAttribute<T>() != null)
.Select(builderFunc);
foreach (var type in types)
{
builder.AddBinding(type.Create());
}
}
AddBindings<ResolverAttribute>(t =>
{
var attribute = t.GetCustomAttribute<ResolverAttribute>();
return ResolverTypeBindingBuilder.New()
.SetFieldBinding(BindingBehavior.Implicit)
.SetResolverType(t)
.SetType(attribute.Of);
});
AddBindings<ComplexTypeAttribute>(t =>
ComplexTypeBindingBuilder.New()
.SetFieldBinding(BindingBehavior.Implicit)
.SetType(t));
return builder;
}
}
}