I am trying to use GraphQL
with a legacy service which returns a JSON with some of the keys as integer. Here is an example,
{
"id": 1234,
"image": {
"45": "image1url",
"90": "image2url"
},
"name": "I am legacy server"
}
When I tried to define "45
" as GraphQL
field,
var imageType = new graphql.GraphQLObjectType({
name: 'Image',
fields: {
45: { type: graphql.GraphQLString },
90: { type: graphql.GraphQLString }
}
});
I am getting the following error,
Error: Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "45" does not`.
How can we handle keys as integer scenario?
GraphQL only allows keys starting with ASCII character or an underscore. You can use resolve
functions to map old names to new.
var imageType = new graphql.GraphQLObjectType({
name: 'Image',
fields: {
size45: {
type: graphql.GraphQLString,
resolve: (parent) => parent['45'],
},
size90: {
type: graphql.GraphQLString,
resolve: (parent) => parent['90']
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With