0

Is there a practical way to model this type of JSON data structure in a GraphQL schema:

{
    "id": 123,
    "name": "My Parent Object",
    "childWidgets": {
        "456": {
            "id": 456,
            "name": "Child Widget 1"
        },
        "789": {
            "id": 789,
            "name": "Child Widget 2"
        }
    }
}

Specifically, I would like childWidgets to be an associative array of objects keyed by their id values. I understand that field names in GraphQL cannot begin with a digit, but then I am not encoding the id values into the schema in this instance - these are naturally not fixed values. (There may also be cases where the array keys in question are not numeric, but similarly cannot be encoded into the schema due to their variable/ephemeral nature.)

I expect this is a common question, but I've so far only found one related question on the subject. However, that one appears to be about encoding a well defined set of numeric codes into the schema, so not exactly the same.

John Rix
  • 6,271
  • 5
  • 40
  • 46

1 Answers1

4

GraphQL requires all field names to be specified as part of the schema, so it does not support map-like structures where the keys would only be known at runtime. You can either:

  • Return the data as a List and then transform it client-side. This puts more of the work on the client, but also ensures your response can still be normalized correctly by clients like Apollo.

  • Return a custom scalar. This lets you return any valid JSON value, at the expense of a lack of validation and documentation.

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183