当键是整数类型时,GraphQL 返回“名称必须匹配”错误

Posted

技术标签:

【中文标题】当键是整数类型时,GraphQL 返回“名称必须匹配”错误【英文标题】:GraphQL is returning "Names must match" error when the Key is of type integer 【发布时间】:2016-08-03 15:52:24 【问题描述】:

我正在尝试将 GraphQL 与旧服务一起使用,该服务返回 JSON,其中一些键为整数。这是一个例子,


  "id": 1234,
  "image": 
    "45": "image1url",
    "90": "image2url"
  ,
  "name": "I am legacy server"

当我尝试将"45" 定义为GraphQL 字段时,

var imageType = new graphql.GraphQLObjectType(
  name: 'Image',
  fields: 
    45:  type: graphql.GraphQLString ,
    90:  type: graphql.GraphQLString 
  
);

我收到以下错误,

错误:名称必须匹配 /^[_a-zA-Z][_a-zA-Z0-9]*$/ 但“45”不匹配。

我们如何将键处理为整数场景?

【问题讨论】:

【参考方案1】:

GraphQL 只允许以 ASCII 字符或下划线开头的键。您可以使用resolve 函数将旧名称映射到新名称。

var imageType = new graphql.GraphQLObjectType(
  name: 'Image',
  fields: 
    size45:  
      type: graphql.GraphQLString,
      resolve: (parent) => parent['45'],
    ,
    size90:  
      type: graphql.GraphQLString,
      resolve: (parent) => parent['90']
    
  
);

【讨论】:

以上是关于当键是整数类型时,GraphQL 返回“名称必须匹配”错误的主要内容,如果未能解决你的问题,请参考以下文章