admin管理员组

文章数量:1279242

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 receive the following 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: i

nternal 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 quieries to return value without errors

本文标签: cIssue with entity retrieval by ID when using the Relay approachStack Overflow