0

I have an issue with entity retrieval by ID when using the Relay approach.

When I send this request:

query simpleQuery {
  getSchemaInfo(Id: "U2NoZW1hSW5mbzq0cC2Zq7keTLzUWk7aem8Y") {
    name
  }
}

I get this error:

No serializer registered for type SchemaInfo

However, when I send a Relay request:

query relayQuery {
  node(id: "U2NoZW1hSW5mbzq0cC2Zq7keTLzUWk7aem8Y") {
    ... on SchemaInfo {
      name
    }
  }
}

Everything works fine.

I investigated HotChocolate during execution and found only one difference.

Let's look at the ParseLiteral method of InputParser(ParseLiteral method of InputParser). In the case of simpleQuery, there is an IdFormatterpresent for the Id field (IdFormatter present for the Id field in ParseLiteral method), which leads to the Format method of this formatter being called (Format method of formatter). This then leads to a call of the Parse method of OptimizedNodeIdSerializer (Parse method of OptimizedNodeIdSerializer). In this method, valueSerializer is not initialized because IsSupported of GuidNodeIdValueSerializer with IdType as parameter is called and returns false. This leads to SerializerMissing throwing an exception. IsSupported returns false because the input parameter has type IdType, not Guid (IsSupported method of GuidNodeIdValueSerializer).

In the case of relayQuery, no formatter is present for IdField in the ParseLiteral method of InputParser (ParseLiteral method of InputParser in case of relayQuery). Because of that, the Format method isn't called and FormatValue returns the value variable (FormatValue method). That's why everything works fine. Could you please help me understand what I'm missing?

I create the Schema dynamically based on entities from a specific assembly. Here is how my Program.cs looks like:

private static void AddSchemaTypes(IRequestExecutorBuilder builder)
{
    // get entities from assembly
    typeof(Entity).Assembly.GetTypes()
        .Where(t => t.IsSubclassOf(typeof(Entity)))
        .ForEach(t => builder
        // add type that will be returned from query
            .AddType(typeof(EntityType<>).MakeGenericType(t))
        // add query for this entity
            .AddTypeExtension(typeof(QueryType<>).MakeGenericType(t)));

    builder.
        ConfigureSchema(b => b.AddRootType(
            new ObjectType(d => d.Name(OperationTypeNames.Query)),
            OperationType.Query));
}

private static void Main(string[] args)
{
    ConfigurationProvider.ConnectionStrings.MustNotBeNull();

    DatabaseInitializer.Initialize(ConfigurationProvider.ConnectionStrings.PostgresConnectionString);

    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddHttpContextAccessor();
    builder.Services.AddSingleton(new TransactionScopeHandler(new(ConfigurationProvider.ConnectionStrings.PostgresConnectionString)));
    builder.Services.AddGraphQLServer()
        .AddTransactionScopeHandler(s => s.GetService<TransactionScopeHandler>().MustNotBeNull())
        .AddFiltering()
        .AddSorting()
        .AddProjections()
        .ModifyPagingOptions(opt => opt.IncludeTotalCount = true)
        .AddGlobalObjectIdentification()
        .AddInMemorySubscriptions();
    AddSchemaTypes(builder.Services.AddGraphQL());

    var app = builder.Build();
    app.UseHttpsRedirection();
    app.UseWebSockets();
    app.MapGraphQL();
    app.RunWithGraphQLCommands(args);
}

Here is how EntityType looks like:

internal class EntityType<T> : ObjectType<T>
    where T : Entity, new()
{
    protected override void Configure(IObjectTypeDescriptor<T> descriptor)
    {
        descriptor.MustNotBeNull();

        descriptor
            .Description("description");

        descriptor
            .ImplementsNode()
            .IdField(f => f.Id)
            .ResolveNode(Query.GetAsync<T>);

        typeof(T).GetProperties().ForEach(property =>
        {
            var prop = descriptor
                .Field(property)
                .Description(info.Name);

            if (property.Name is nameof(Entity.Id))
            {
                prop.ID();
            }
        });
    }
}

Here is how QueryType looks like:

internal class QueryType<T> : ObjectTypeExtension
    where T : Entity, new()
{
    protected override void Configure(IObjectTypeDescriptor descriptor)
    {
        descriptor.Name(OperationTypeNames.Query);

        descriptor
            .Field($"get{typeof(T).Name}")
            .Description("some description")
            .Type<EntityType<T>>()
            .Resolve(async context => await Query.GetAsync<T>(context, default!))
            .Argument(nameof(Entity.Id), a => a
                .Description("some description")
                .Type<IdType>()
                .ID<T>());

        descriptor
            .Field($"get{typeof(T).Name}Collection")
            .Description("some description")
            .Type<ListType<EntityType<T>>>()
            .Resolve(Query.Get<T>)
            .UseOffsetPaging()
            .UseProjection()
            .UseFiltering()
            .UseSorting();
    }
}

This is how Entity looks like:

public abstract class Entity
{
    public Guid Id { get; set; }

    public DateTime? Timestamp { get; set; }
}

I have tried to change generic argument in Type<> method of QueryType from IdType to StringType, UUID type but IdType is still passed in to ParseLiteral method. I expect both queries to return value without errors

1 Answer 1

0

I'm not sure if you are facing the same problem as I did, but I had this issue when I was trying to use Ulid type for IDs.

After an hour of debugging I found out that HotChocolate automatically creates lots of Id serializers, but they do not provide Ulid ID serializer.

But you can register yours:

#1 Create class

using System.Diagnostics.CodeAnalysis;

namespace SocialMediaMonitor.GraphQL.Types;

internal sealed class UlidNodeIdValueSerializer: INodeIdValueSerializer
{
    public bool IsSupported(Type type) => type == typeof(Ulid) || type == typeof(Ulid?);

    public NodeIdFormatterResult Format(Span<byte> buffer, object value, out int written)
    {
        if (value is Ulid u)
        {
            return System.Text.Encoding.UTF8.TryGetBytes(u.ToString(), buffer, out written)
                ? NodeIdFormatterResult.Success
                : NodeIdFormatterResult.BufferTooSmall;
        }

        written = 0;
        return NodeIdFormatterResult.InvalidValue;
    }

    public bool TryParse(ReadOnlySpan<byte> buffer, [NotNullWhen(true)] out object? value)
    {
        var conversion = Ulid.TryParse(buffer, out var result);
        value = result;
        return conversion;
    }
}

#2 Register it

builder.Services.AddSingleton<INodeIdValueSerializer>(sp => new UlidNodeIdValueSerializer());

Hope it will help!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your suggestion! Unfortunately we've decided not to use Relay anymore because of pure frontend libraries

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.