Generated code with union Query

Hello,

I have an error when I query a union type.
The code generator ask me to query each type of the union.

Example :

the type :

union Content = Article|Author|Recipe

the part of the query (I only want articles)

            edges {
                node {
                    ... on Article {
                        id
                    }
                }
            }

At compile time, I have this message :

Key Field(s) ‘[id]’ are not queried on Author at…

Should I query all types or maybe union is misused ? Or a bug ?

Thanks

Hi!

The results of your query can still contain Authors even if they won’t contain any fields.

If you have configured the cache to use id as the key field for Author, then this field is needed and must be queried so the cache can use it. In most cases, id fields are automatically added to queries in a transparent way. But in cases like this one with unions, this cannot be done automatically.

One way to fix this is to add a case for Author too:

            edges {
                node {
                    ... on Article {
                        id
                    }
                    ... on Author {
                        id
                    }
                }
            }

I understand. Our query set a parameter to get only Article.

But the fix is, actually, not possible.
We should use an alias for the id of the Author.
And when we use the alias like this :

edges {
    node {
          ... on Article {
              id
          }
          ... on Author {
              authorId : id
          }
    }
}

The compiler print the same message :

Key Field(s) ‘[id]’ are not queried on Author at Operation…

I feel stuck in a loop :grinning:

Hello,
should I create an issue for usage of alias in union query ?
Thanks

Hi! I’m sorry, I missed your previous message!

When using an alias like you do, the server will not reply with an id but with authorId, which means the id cannot be seen and used in the key, and therefore Apollo will still complain it is missing. Why can’t you use id directly?

Hello,
You are right, it works.
I have an issue with our schema, some id fields are nullable and some non nullable.
I will update our schema to get consistent id non nullability.
Thanks !