Vladimir Alexiev
Vladimir Alexiev

Reputation: 2601

is this GraphQL query valid?

Assume a simple schema like

interface Character {name:String!}
type Human implements Character {name:String!}
type Droid implements Character {name:String!}
type Query {
  characters: [Character!]
}

This query is not valid because it does not select down to leaf (scalar) fields (see https://graphql.github.io/graphql-spec/draft/#sec-Leaf-Field-Selections):

{characters {
}}

Is this query valid? It selects a scalar field, but only for Human. It'd return Droids without any fields.

{characters {
   ... on Human {name}
}}

Upvotes: 0

Views: 320

Answers (1)

TomDT
TomDT

Reputation: 329

(Copying response from issue)

Actually, I think that it is valid. The spec says :

  • If selectionType is an interface, union, or object

The subselection set of that selection must NOT BE empty

It simply states that it must contain a subselection (could be an inline fragment as in your example). It doesn't specify that its subselections must be leaf field selections.

I agree that in essence it should actually contain leaf selections for every possible subtype of the field's return type (e.g Human and Droid in your scenario), otherwise it could return an empty response. For instance, if there are no humans and 3 droids in your database then it would return:

{
    "character" : [{}, {}, {}] 
}

This also happens with union types, you are not obliged to specify each concrete type and therefore can get empty results.

I imagine there must be some reason related to fragments ?

Upvotes: 1

Related Questions