Reputation: 471
I have an object with some properties but unable to define the schema. Structure of the object
{
"1": {
average: 40,
count: 15
},
"2": {
average: 11,
count: 2
},
"3": {
average: 30,
count: 2
}
}
My schema
const typeDef = gql`
type Query {
scoreByRank: Count
}
type Count {
"1": obj
"2": obj
"3": obj
}
type obj{
average: Int
count: Int
}
`;
But this query is failing because of the object prop with "1", "2" etc. Is there a better way to build this schema?
Upvotes: 0
Views: 542
Reputation: 3751
GraphQL field names must follow certain rules. Specifically /^[_a-zA-Z][_a-zA-Z0-9]*$/
. As you can see, a field name must not start with a number 0-9. Certain field names might be inconvenient for a consumer of your GraphQL API depending on what languages they are using. The field name restrictions are defined so that most common languages can easily use the data provided by a GraphQL API.
The recommended solution is to follow the rules and come up with better field names, like _1
, two
or field3
.
You could return an array instead of an object, but there is currently no easy way of enforcing a specific length for an array. On top of that, the indexing of an array would start at 0 rather than 1.
You could define a custom scalar for your object, but then you would lose the ability to leave out unnecessary fields and it would require far more convoluted code to work. As such, I would consider it bad practice. Only do it if you're dealing with an inflexible and opaque third party application that leaves you no other way.
Upvotes: 1