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
First, the ID scalar type is part of GraphQL standard, and defined as:
Relay is a GraphQL client JavaScript framework for React applications. Apollo GraphQL is another alternative.
HotChocolate has a few helpers to enable "Relay-style GraphQL API". These helpers will convert the id-field to a base64-encoded hash, serialized as a string. This is a good thing because:
Even though you enable "Relay support" in HotChocolate, you don't have to use Relay, you can still use any GraphQL client (Apollo client is my favourite)
Now, if you just want to use the GraphQL ID scalar type, you can try this as I suggested first:
First remove ID-attribute from query:
then specify ID scalar type like this:
But if you want to enable "Relay support" in HotChocolate, follow Arsync's answer (I changed this to HotChocolate v11 which has slightly different syntax):
Update for Hot Chocolate v12: It's now possible to enable global identification, but without other relay related stuff:
Then in your type definition:
Or even simpler with v12:
If you try to query for employees now you'll see that id is not an integer, but a hash. Something like "TGFuZ3VhZ2UKaTE=". This hash is generated by HotChocolate, see IdSerializer source. If you try to base64 decode this string:
The errormessage you received "The ID
1
has invalid format", is because it now expects a hashed string, and not an integer.This query should work: