Search code examples
graphqlreact-apollographene-python

How to Query nullable data that contains non-null fields via GraphQL?


Let's say I have data structured as follows:

house: {
    id: Int,
    address: String,
    neighborhood (Foreign Key, Nullable): {
        id: Int,
        name: String,
        city (Foreign Key, Nonnull): {
            id: Int (Nonnull)
            name: String
        }
    }
}

and I am constructing the following query:

{
    homes {
        house {
            id
            address
            neighborhood {
                id
                name
                city {
                    id
                    name
                }
            }
        }
    }
}

GraphQL (React Apollo frontend, Graphene + Django backend) complains that I'm trying to return null for non-null city.id when I attempt this query. This occurs specifically for houses that don't have a neighborhood (and in turn no city), so it attempts to return city.id as null when it shouldn't actually get that deep into the data structure since the parent neighborhood is null.

I'm trying to get valid neighborhood details (including city) when they are available, and null neighborhood when they are not. What is the appropriate approach for this?


Solution

  • The issue I was having had to deal with the data in my database. The query above works as desired, but I had some corrupt data that was breaking the query from completing successfully.

    I was able to debug this using https://github.com/graphql/graphiql which let me make GQL queries in quick succession, helping me probe exactly what data field was triggering my error.