apollographql / apollo-kotlin

:rocket:  A strongly-typed, caching GraphQL client for the JVM, Android, and Kotlin multiplatform.
https://www.apollographql.com/docs/kotlin
MIT License
3.75k stars 651 forks source link

Key Field(s) '[id]' are not queried on XUnion at Operation(XQuery).union #5174

Open sonatard opened 1 year ago

sonatard commented 1 year ago

Version

3.8.2

Summary

I have set the extend interface Node @typePolicy(keyFields: "id").

And when I build, the following error occurs. Key Field(s) '[id]' are not queried on X2 at Operation(XQuery).union

Steps to reproduce the behavior

union X = X1 | X2

type Query {
 x: X!
}

type X1 {
 id: ID!
 name: String
}

type X2 {
 id: ID!
 name: String
}
extend interface Node @typePolicy(keyFields: "id")
query XQuery {
  x {
    ... on X1 {
       id
       name
    }
  }
}

I found a workaround. By modifying the Query as follows, the error disappears.

query XQuery {
  x {
    ... on X1 {
       id
       name
    }
    ... on X2 {
       id
    }
  }
}

Logs

Key Field(s) '[id]' are not queried on X2 at Operation(XQuery).union

martinbonnin commented 1 year ago

Hi 👋

The reason this error is thrown is because we can't add id on an union field:

query XQuery {
  x {
    # This does not validate as no field except __typename can be queried on unions
    id 
    ... on X1 {
       name
    }
  }
}

We could add fragments that query id on all types automatically:

query XQuery {
  x {
    # fragments added by the Apollo compiler
    ... on X1 {
       id 
    }
    ... on X2 {
       id 
    }
    # etc... if more types in the union

    # original fragment 
    ... on X1 {
       name
    }
  }
}

But we have always resisted doing so because it felt like a larger modification of the user query that could be surprising.

Do you think adding the fragments automatically would help in that case?