Kolia Ukrainec
Kolia Ukrainec

Reputation: 85

Query organization with HotChocolate

I'm trying to organize my query in such way

public class RootQueryType : ObjectType
    {
        protected override void Configure(IObjectTypeDescriptor descriptor)
        {
            descriptor.Include<UserQuery>().Name("userQuery");

            descriptor.Include<MessageQuery>().Name("messageQuery");
        }
    }

But in my Altair playground I end up with this: Altair Documentation

There is no userQuery, but I still can query fields from it. I think that it is not the way Include should work and I'm looking for a way to get messageQuery and userQuery separated.

Upvotes: 0

Views: 899

Answers (2)

Pascal Senn
Pascal Senn

Reputation: 1912

Include returns the IObjectTypeDescriptor So what you re doing is you are setting the name of RootQueryType

If I understand you correctly you would like to be able to query like this:

{
    userQuery {
      userName
    }
    messageQuery {
      message
    }
}
public class RootQueryType : ObjectType
    {
        protected override void Configure(IObjectTypeDescriptor descriptor)
        {
            descriptor.Field("userQuery").Resolve(new UserQuery())
            descriptor.Field("messageQuery").Resolve(new MessageQuery())
        }
    }

In case you want to actually combine the types, and be able to create a query like this:

  
{ 
    userName  
    message 
}

You can use ObjectTypeExtensions

[ExtendObjectType("Query")]
public class UserQuery {
    public string GetUserName() => ...
  
}
[ExtendObjectType("Query")]
public class MessageQuery {
    public string Message() => ...
  
}

You can then do

services.AddGraphQLServer()
   .AddQueryType(x => x.Name("Query"))
   .AddTypeExtension<UserQuery>()
   .AddTypeExtension<MessageQuery>()
   

Upvotes: 1

Michael Ingmar Staib
Michael Ingmar Staib

Reputation: 1927

Include merges all the fields of the included type into the current type. Name refers to the name of the current type. In order to get another level in your type just create a field that returns the new type.

Did you know that you do not need these type descriptors but can just express everything with pure C#.

public class Query 
{
    public UserQuery GetUsers() => new UserQuery();
}

public class UserQuery 
{
    ...
}

This will result in:

type Query {
  users: UserQuery
}

type UserQuery {
  # ...
}

Upvotes: 3

Related Questions