简体   繁体   中英

Type-inheritance in HotChocolate GraphQL

HotChocolate queries seem to always return the base class when I try to return something which inherits from a registered type. Example:

Models:

public interface ICar { int Wheels { get; } }
public class Car  : ICar { public int Wheels => 4; }
public class Bus : Car { }

Query:

public class MyQuery
{
    public ICar Test() { return new Bus(); }
}

Startup:

services.AddGraphQLServer()
        .AddQueryType<MyQuery>()
        .AddType<Car>()
        .AddType<Bus>()

GraphQL Query:

query { 
  test {
    __typename
  } 
}

Output:

{
  "data": {
    test": {
      "__typename": "Car"
    }
  }
}   

I would expect "__typename" in the output to be "Bus". I would expect the same behavior if I dropped the interface and have the return-type of the query set as "Car". I'd be happy to hear any ideas about why it behaves this way and how to resolve this.

The issue here is that GraphQL has no concept of inheritance. GraphQL object types can implement interfaces. Also GraphQL interfaces can implement interfaces.

So, there is no Bus implementing Car in the GraphQL schema in this case. You can print the schema to verify how the C# code was translated to GraphQL.

You still can use base classes as interfaces and build kind of your inheritance tree, but in this case Car can never be a concrete instance.

services
    .AddGraphQLServer()
    .AddQueryType<Query>()
    .AddInterfaceType<Car>()
    .AddType<Bus>();

This would translate to:

type Bus implements Car & ICar {
# shortened fro brevity 
}

interface Car implements ICar {
# shortened fro brevity 
}

interface ICar {
# shortened fro brevity 
}

This makes no sense with your types actually but to give you an idea.

Can you still raise an issue on our GitHub repository? We probably should throw a schema exception hinting at the issue here.

If you want to read into the GraphQL specification on object types it can be done here: https://spec.graphql.org/draft/#sec-Objects

And interfaces are specified here: https://spec.graphql.org/draft/#sec-Interfaces

Hot Chocolate already implements the new 2021 spec draft.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM