Search code examples
graphqlgraphql-java

Datafetcher for nested types in graphql


I am using graphql and graphql-java for a simple API that fetches projects and its assignee

schema {
  query: Query
}

type Query {
   projects: [Project]
   users: [User]
}

type Project {
   id: ID!
   name: String
   assignee : User
   status: String

}

type User {
   id: ID!
   name: String
}

I already have following resolvers:

private RuntimeWiring buildRunTimeWiring() {
return RuntimeWiring.newRuntimeWiring()
    .type("Query", typeWiring -> typeWiring
    .dataFetcher("projects", allProjectsDataFetcher)
    .dataFetcher("users", allUserDataFetcher)
    ).build();
}

How should I write my resolvers so that when I query

projects {
  id
  name
  assignee
}

it should return projects and its assignees. Is it even possible ?


Solution

  • Not sure about your resolver code (which looks good to me) and hope its resolves Project and associated assignee inside that object, I see problem in your graphQL schema (if you are expecting list of users). It should look like ...

    type Project {
       id: ID!
       name: String
       assignee : [User]
       status: String
    }
    

    Make sure you return Object which should look like

    {id:1, name:"someName",status:"Active", assignee :[{id:003, name:"A"}, {id:004, name:"B"}]}