【问题标题】:GraphQL processing array json dataGraphQL处理数组json数据
【发布时间】:2019-06-19 19:37:17
【问题描述】:

我是 GraphQL 新手,不确定这个问题是我缺乏 JavaScript 知识还是 GraphQL。

我的 GraphQL 查询外部服务,当响应是标量 json 对象时,一切正常。当外部服务返回一个 json 数组时,问题就来了。

这适用于单个 json 结果:

const transform = (json) => {
  return {
    id: json.id,
    fullname: json.fullName,
    email: json.email
}

但是对于这样的数组,映射代码是不够的。

[{id:...fullname:...email:...},{id:...etc},{id:...etc}]

现在我可以检测到返回是一个数组,我可以循环遍历数组,只是不确定如何映射到 GraphQLList。

所以在谷歌搜索后,我找到了 GraphQLList,但它也不起作用。

...snip from Schema...
UserData: {
        type: GraphQLLIst(UserType),

与上面相同的映射代码。

message": "预期为 Iterable,但没有为字段 RootQueryType.investorData 找到一个。

但是我很困惑,因为控制台日志清楚地显示了一个json数组?


GraphQLSchema

const RootQueryType = new GraphQLObjectType({
   name: 'RootQueryType',
   fields:{
    investorData: {
        type: new GraphQLList(UserType),
        description: 'Get investors by id',
        args:{key: {type: GraphQLString} },
        resolve: resolveInvestorData
       }
     }
   }
})

【问题讨论】:

  • 您能发布您的 GraphQL 架构吗?您为investorData 字段定义的类型是什么?
  • @YevheniiHerasymchuk。架构已发布。

标签: javascript graphql


【解决方案1】:

问题解决了,但不是我的任何天才,而是愚蠢的运气。

所以通过添加映射代码,我实际上是在干扰 GraphQL 的映射。

这是错误的,但在这里发布是为了前后比较。

GraphQLSchema:

const RootQueryType = new GraphQLObjectType({ 名称:'RootQueryType',

fields: {    
    userData: {
        type: new GraphQLList(UserType),
        args:{key: {type: GraphQLString} },
        resolve: resolveUserData
       }
    }
  }
})

解析用户数据:

return fetch(url)
   .then(response => {
      return response.json()
      })
   .then(json => {
      return transformUser(json)
      })
   .catch(err => {
      console.trace(err)
     })  
  }

const transformUser = (json) => {
  console.trace(json);
  return {
    id: json.id,
    portfolioid: json.portfolioID,
    fullname: json.fullName,
    email: json.email
   }
}

正确的返回数据映射。 (提示没有映射)

return fetch(url)
   .then(response => {
      return response.json()
      })
   .catch(err => {
      console.trace(err)
     })  
  }

现在这是我的最终解决方案,因为我想要一个端点来处理单个查找和“获取所有”请求。随意评论这个架构。

const resolveUserData = (obj, args) => {

let url = '';

//if branch to determine if one user or all
if (typeof args.key === "undefined") {
    url = 'http://localhost:5001/api/users';
}
else
{
    url = 'http://localhost:5001/api/users/' + args.key;
}

return fetch(url)
.then(response => {
  return response.json()
})
.then(json => {
    if(!Array.isArray(json))
    {
        var jarray = [];
        jarray.push(json);
        return jarray;
    }
    return json
})
.catch(err => {
  console.trace(err)
})  

}

【讨论】:

    猜你喜欢
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 2020-08-04
    • 2020-07-05
    相关资源
    最近更新 更多