Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL is returning "Names must match" error when the Key is of type integer

Tags:

graphql

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?

like image 434
rocky Avatar asked Mar 13 '23 15:03

rocky


1 Answers

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']
    }
  }
});
like image 183
freiksenet Avatar answered Apr 30 '23 04:04

freiksenet