如何从 REST API 为多个或嵌套的 json 数据定义数组类型

问题描述

我是 GraphQL 的新手。我在使用 express-graphql 服务器从 API 获取数组数据时遇到问题,我发现在某个地方很难解决。这是场景。

我有一个来自 REST API 的 GET 数据,它的响应类似于这样:

{
    "id": 1,"name": "billy","foods": [
        {
            "food":{
                "name":"crepes","taste": "crunchy"
            }
        },{
            "food":{
                "name":"noodle","taste":"spicy"
            }
        },]
}

在我的架构中,我成功地获得了 idname,我是这样实现的:

const FoodsType= new GraphQLObjectType({
  name: 'foods',fields: () => ({
    id:{ type: GraphQLInt },name:{ type: GraphQLString},foods: { type: GraphQLArray}
  })
});

正如您在上面的代码中看到的,我无法获取包含数组数据的食品数据,因为没有像 GraphQLArray 这样的标量类型。 我的问题是我们如何获得包含多个 json 数据 foodsfood 数据?

解决方法

const ResType= new GraphQLObjectType({
   name: 'response',field:() => ({
       name: {type: GraphQLString},taste: {type: GraphQLString}
   })
   
});


const FoodsType= new GraphQLObjectType({
  name: 'foods',fields: () => ({
    id:{ type: GraphQLInt },name:{ type: GraphQLString},foods: { type: new GraphQLList(ResType)}
  })
});
,

经过一些尝试,我终于通过定义每个深度级别的类型来解决这个问题。这是我对架构文件的回答。

  const FoodsType = new GraphQLObjectType({ 
    name: 'foods',fields: () => ({
      id:{ type: GraphQLInt },name: { type: GraphQLString },foods:{ type: new GraphQLList(FoodType) }
    })
  });
  
  const FoodType = new GraphQLObjectType({
    name: 'food',fields: () => ({
      food: {type: FoodDetail}
    })
  });
  
  const FoodDetail = new GraphQLObjectType({
    name: 'fooddetail',fields: () => ({
      name:{ type: GraphQLString },taste:{ type: GraphQLString}
    })
  });

这是我从 API 获得的解析器

  const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',fields: {
      foods: {
        type: FoodsType,args: {
          id: { type: GraphQLInt }
        },resolve(parent,args) {
          return axios
            .get(`https://hereisanapi/${args.id}`)
            .then(res => {
              return res.data;
            });
        }
      }
    }
  });

然后在 GraphQL Query 中我把这个。

{
  foods(id:1){
    food{
      name,taste
    }
  }
} 

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...