Error “The ID `1` has an invalid format” when querying HotChocolate

南楼画角 提交于 2021-02-11 17:58:01

问题


Tried to make own project, looking to ChilliCream/graphql-workshop as example.

There is a part, where id parameter of a query marked with IDAttribute.

Description of ID type says following:

The ID scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as "4") or integer (such as 4) input value will be accepted as an ID.

My C# query source looks like

[ExtendObjectType(Name = GraphqlQueryNames.Query)]
public class EmployeeQuery
{
    public async Task<Employee> GetEmployeeByIdAsync(
        [ID] int id,
        [Service] IEmployeeRepository employeeRepository,
        CancellationToken token)
    {
        return await employeeRepository.GetEmployeeByIdAsync(id, token);
    }
}

And in playground:

# 1 passed as value of $id

query getEmployeeById($id: ID!) {
  employeeById(id: $id) {
    familyName
  }
}

Whether value is a string or a number, server throws same error "The ID `1` has an invalid format".

If we remove the [ID] attribute from C# and use it as 'Int!' in GraphQL query, it works fine.

What's wrong with ID and why it exists in example (AttendeeQueries.cs)? HotChocolate 10.5.3


回答1:


Found that IDAttribute is for Relay (as it located in HotChocolate.Types.Relay namespace). So need enable and configure Relay support (source):

ISchema schema = SchemaBuilder.New()
    .EnableRelaySupport()
    ...
    .Create();

And in ObjectType:

public class MyObjectType
    : ObjectType<MyObject>
{
    protected override void Configure(IObjectTypeDescriptor<MyObject> descriptor)
    {
        descriptor.AsNode()
            .IdField(t => t.Id)
            .NodeResolver((ctx, id) =>
                ctx.Service<IMyRepository>().GetMyObjectAsync(id));
        ...
    }
}

Seems the example project graphql-workshop needs more in-place explanation of purpose for these things. Can be found here.



来源:https://stackoverflow.com/questions/64226770/error-the-id-1-has-an-invalid-format-when-querying-hotchocolate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!