Skip to content

Instantly share code, notes, and snippets.

@stand-sure
Last active July 8, 2022 22:41
Show Gist options
  • Save stand-sure/0f8cc546cfb3bc59fda88c84bc194e51 to your computer and use it in GitHub Desktop.
Save stand-sure/0f8cc546cfb3bc59fda88c84bc194e51 to your computer and use it in GitHub Desktop.
HotChocolate trimming strings in inputs
using HotChocolate.Language;
using JetBrains.Annotations;
[PublicAPI]
public class TrimmedStringType : ScalarType<string, StringValueNode>
{
/// <summary>
/// Initializes a new instance of the <see cref="TrimmedStringType" /> class.
/// </summary>
public TrimmedStringType() : base(new NameString("TrimmedString"))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TrimmedStringType" /> class.
/// </summary>
public TrimmedStringType(
NameString name,
string? description = null,
BindingBehavior bind = BindingBehavior.Explicit)
: base(name, bind)
{
this.Description = description;
}
public override IValueNode ParseResult(object? resultValue) => this.ParseValue(resultValue);
protected override string ParseLiteral(StringValueNode valueSyntax) => valueSyntax.Value.Trim();
protected override StringValueNode ParseValue(string runtimeValue) => new(runtimeValue.Trim());
}
public record TSDemoInput(string Name);
public class TSDemoInputType : InputObjectType<TSDemoInput>
{
protected override void Configure(IInputObjectTypeDescriptor<TSDemoInput> descriptor)
{
descriptor.Field(input => input.Name)
.Type<TrimmedStringType>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment