Scalars
Scalars are created as instances of ScalarType
.
Built-in
These are provided as static properties on ScalarType
.
ScalarType.Boolean
ScalarType.Int
ScalarType.ID
ScalarType.Float
ScalarType.String
In addition following non-null instances are provided for convenience.
ScalarType.NonNullBoolean
ScalarType.NonNullInt
ScalarType.NonNullID
ScalarType.NonNullFloat
ScalarType.NonNullString
Also standard collection is provided
Standard =
new List<(ScalarType Type, IValueConverter Converter)>()
{
(String, new StringConverter()),
(Int, new IntConverter()),
(Float, new DoubleConverter()),
(Boolean, new BooleanConverter()),
(ID, new IdConverter())
}
Custom scalars
Create instance of ScalarType
and provide name and metadata. Value converter
is also needed when building schema with custom scalar in it.
Example:
Scalar:
ID = new ScalarType(
"ID",
"The ID scalar type represents a unique identifier, often used to refetch an object" +
" or as the key for a cache. The ID type is serialized in the same way as a String; " +
"however, it is not intended to be human‐readable. While it is often numeric, it " +
"should always serialize as a String.")
Converter:
using System;
using System.Globalization;
using System.Text;
using Tanka.GraphQL.Language.Nodes;
namespace Tanka.GraphQL.TypeSystem.ValueSerialization
{
public class IdConverter : IValueConverter
{
public object? Serialize(object? value)
{
if (value == null)
return null;
return Convert.ToString(value, CultureInfo.InvariantCulture);
}
public ValueBase SerializeLiteral(object? value)
{
var serializedValue = Serialize(value);
if (serializedValue == null)
return new NullValue();
return new StringValue(Encoding.UTF8.GetBytes((string)serializedValue));
}
public object? ParseValue(object? input)
{
if (input == null)
return null;
return Convert.ToString(input, CultureInfo.InvariantCulture);
}
public object? ParseLiteral(ValueBase input)
{
if (input.Kind == NodeKind.NullValue)
{
return null;
}
if (input.Kind == NodeKind.StringValue)
return (StringValue)input.ToString();
throw new FormatException(
$"Cannot coerce Id value from '{input.Kind}'");
}
}
}