Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is graphql-dotnet returning "Expected non-null value" error for this schema?

I have a simple schema that I'm trying to query as follows:

{
  subQuery {
    subObjectGraph {
      Name
    }
  }
}

But "graphiql" throws the following error, without even seeming to run my query.

{
  "errors": [
    {
      "message": "Expected non-null value, resolve delegate return null for \"$Api.Schema.Queries.MySubObjectGraphType\"",
      "extensions": {
        "code": "INVALID_OPERATION"
      }
    }
  ]
}

What is wrong with my schema (below)? I am new-ing up a SubObject, so I don't understand why the error message implies the value is null.

    public class Schema: GraphQL.Types.Schema
    {
        public Schema(IDependencyResolver resolver): base(resolver)
        {
            Query = resolver.Resolve<RootQuery>();  
            Mutation = null;
        }
    }

    public class RootQuery: ObjectGraphType
    {
        public RootQuery(IDependencyResolver resolver)
        {
            Name = "Query";

            Field<MySubQuery>(
                name: "subQuery",
                resolve: ctx => resolver.Resolve<MySubQuery>());
        }
    }


    public class MySubQuery: ObjectGraphType
    {
        public MySubQuery()
        {
            Name = "TempSubQuery";

            Field<StringGraphType>("SubQueryName", resolve: ctx => "Some string value");

            Field<MySubObjectGraphType>(
                name: "subObjectGraph",
                resolve: ctx => FetchFromRepo());
        }


        //Repo access would go here, but just new-ing the object for now.
        private SubObject FetchFromRepo()
        {
            return new SubObject() { Name = "some sub object" };
        }
    }


    public class SubObject
    {
        public string Name { get; set; }
    }

    public class MySubObjectGraphType: ObjectGraphType<SubObject>
    {
        public MySubObjectGraphType()
        {
            Name = "MySubObject";
            Description = "An object with leaf nodes";

            Field(l => l.Name);
        }
    }

The code works fine if I substitute MySubObjectGraphType with StringGraphType, so the problem must be with configuration of MySubObjectGraphType.

Please help? I'm using v2.4.

like image 295
willem Avatar asked Jan 02 '23 12:01

willem


1 Answers

You need to add a service registration for the MySubObjectGraphType in your Startup.cs

So the rule could be described as "custom types deriving from ObjectGraphType must be registered via dependency injection at some point"

e.g in Startup.cs:

services.AddSingleton<MySubObjectGraphType>();

like image 62
JPThorne Avatar answered Jan 05 '23 15:01

JPThorne