-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUseConvertUnitAttribute.cs
50 lines (47 loc) · 1.6 KB
/
UseConvertUnitAttribute.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
using System;
using System.Reflection;
using HotChocolate.Types;
using HotChocolate.Types.Descriptors;
namespace StarWars.Characters
{
[AttributeUsage(
AttributeTargets.Property | AttributeTargets.Method,
AllowMultiple = false)]
public sealed class UseConvertUnitAttribute
: DescriptorAttribute
{
protected override void TryConfigure(
IDescriptorContext context,
IDescriptor descriptor,
ICustomAttributeProvider element)
{
if (descriptor is IObjectFieldDescriptor objectField)
{
objectField
.Argument("unit", a => a.Type<EnumType<Unit>>().DefaultValue(Unit.Meters))
.Use(next => async context =>
{
await next(context).ConfigureAwait(false);
if (context.Result is double length)
{
//NOTE: Updated to use v11 method...
context.Result = ConvertToUnit(length, context.ArgumentValue<Unit>("unit"));
}
});
}
else if (descriptor is IInterfaceFieldDescriptor interfaceField)
{
interfaceField
.Argument("unit", a => a.Type<EnumType<Unit>>().DefaultValue(Unit.Meters));
}
}
private double ConvertToUnit(double length, Unit unit)
{
if (unit == Unit.Foot)
{
return length * 3.28084d;
}
return length;
}
}
}