Brain Up
Brain Up

Reputation: 163

GraphQL : Get children of specific implementation

I'm getting a GraphQL object with a 'children' field. That field is of the type 'X' and has two different implementations, 'Y' and 'Z'.

So when I'm doing my query I can do this :

{
    fieldOne
    fieldTwo
    children {
        ... on Y {
            fieldOne
            fieldTwo
        }
        ... on Z {
            fieldOne
        }
    }
}

Is there a way for me to only get the children with the Y implementation ?

Because if I'm doing this :

{
    fieldOne
    fieldTwo
    children {
        ... on Y {
            fieldOne
            fieldTwo
        }
    }
}

I will get and object that looks like this :

{
    fieldOne
    fieldTwo
    children [
        {}, // Z implementation
        {}, // Z implementation
        {
            fieldOne,
            fieldTwo
        }, // Y implementation
    ]
}

Thank you :)

Upvotes: 0

Views: 2602

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84867

What you are seeing is expected behavior. From the spec:

Fragments can be defined inline within a selection set. This is done to conditionally include fields based on their runtime type.

Type conditions like ... on Y are just a way to filter what fields are resolved based on the runtime type. They are not a way to filter the actual list of results. In fact, there is no built-in filtering in GraphQL.

In order to filter a list to include only certain types (or based on any other condition), the field in question will need to have some kind of filter argument and resolver logic that uses it to actually do the filtering.

If you're using a third-party API and the schema doesn't support filtering, then as a client there's not much you can do outside of processing the response after the fact.

Upvotes: 1

Related Questions