forked from planetarium/mimir
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add BigIntegerType scalar type for GraphQL (planetarium#344)
- Loading branch information
1 parent
8327773
commit 1f761bb
Showing
2 changed files
with
63 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
using System.Numerics; | ||
using HotChocolate; | ||
using HotChocolate.Language; | ||
using HotChocolate.Types; | ||
using System.Globalization; | ||
|
||
namespace Lib9c.GraphQL.Types; | ||
|
||
public class BigIntegerType : ScalarType<BigInteger, StringValueNode> | ||
{ | ||
public BigIntegerType() : base("BigInteger") | ||
{ | ||
} | ||
|
||
public override IValueNode ParseResult(object? resultValue) | ||
{ | ||
return resultValue switch | ||
{ | ||
BigInteger bigInteger => ParseValue(bigInteger), | ||
string s => ParseValue(s), | ||
_ => throw new SerializationException( | ||
ErrorBuilder.New() | ||
.SetMessage("Invalid runtime type. Expected: BigInteger or string.") | ||
.SetCode(ErrorCodes.Scalars.InvalidRuntimeType) | ||
.Build(), | ||
this) | ||
}; | ||
} | ||
|
||
protected override BigInteger ParseLiteral(StringValueNode valueSyntax) => | ||
BigInteger.Parse(valueSyntax.Value, CultureInfo.InvariantCulture); | ||
|
||
protected override StringValueNode ParseValue(BigInteger runtimeValue) => | ||
new(runtimeValue.ToString(CultureInfo.InvariantCulture)); | ||
|
||
public override bool TrySerialize(object? runtimeValue, out object? resultValue) | ||
{ | ||
if (runtimeValue is BigInteger bigInteger) | ||
{ | ||
resultValue = bigInteger.ToString(CultureInfo.InvariantCulture); | ||
return true; | ||
} | ||
|
||
resultValue = null; | ||
return false; | ||
} | ||
|
||
public override bool TryDeserialize(object? resultValue, out object? runtimeValue) | ||
{ | ||
if (resultValue is string s) | ||
{ | ||
if (BigInteger.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out BigInteger bigInteger)) | ||
{ | ||
runtimeValue = bigInteger; | ||
return true; | ||
} | ||
} | ||
|
||
runtimeValue = null; | ||
return false; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters