Reputation: 649
I'm trying to mirror this Typescript interface as a GQL type:
interface List {
items: [String] | [[String]]
}
My first idea was to keep it simple:
type List {
items: [String]! | [[String]!]!
}
But GQL doesn't like that, so then I tried something like:
type List1D {
items: [String]!
}
type List2D {
items: [[String]!]!
}
union ListItems = List1D | List2D
type List {
items: ListItems
}
But I believe that would result in something like this:
{
items: {
items: [] // union type
}
}
How do I accomplish what I'm actually going for?
Upvotes: 1
Views: 439
Reputation: 158837
The easiest way would be to always package up singleton items into array, and make the schema be
interface List {
"""If the internal representation has a flat array of strings,
it is wrapped into an array of length 1 containing that array."""
items: [[String]]
}
The problem you'll run into here is that unions can only include named object types (see "Type Validation" rule 2).
My experience working with GraphQL has been that you can't model arbitrary JSON with the GraphQL schema language. I would suggest designing an API that you want external callers to be able to use, without really considering what internal implementation types you have; and then once you've designed that API, use resolver functions to map your internal storage into the types and fields required by the API. Don't worry about having additional "layers" of JSON object in the response, if the API is otherwise sensible.
If it is really semantically meaningful to the API consumer whether it is a 1- or 2-dimensional array of results, then the form you've shown is reasonable (and yes, the JSON-format response will have two levels of items:
).
Upvotes: 1