Skip to content

Commit

Permalink
feat: Add BigIntegerType scalar type for GraphQL (planetarium#344)
Browse files Browse the repository at this point in the history
  • Loading branch information
Arindam2002 committed Sep 28, 2024
1 parent 8327773 commit 1f761bb
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
62 changes: 62 additions & 0 deletions Lib9c.GraphQL/Types/BigIntegerType.cs
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;
}
}
1 change: 1 addition & 0 deletions Mimir/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
.AddLib9cGraphQLTypes()
.AddMimirGraphQLTypes()
.BindRuntimeType(typeof(Address), typeof(AddressType))
.BindRuntimeType(typeof(BigIntegerType), typeof(BigIntegerType))
.BindRuntimeType(typeof(HashDigest<SHA256>), typeof(HashDigestSHA256Type))
.AddErrorFilter<ErrorFilter>()
.ModifyRequestOptions(requestExecutorOptions => { requestExecutorOptions.IncludeExceptionDetails = true; });
Expand Down

0 comments on commit 1f761bb

Please sign in to comment.