问题描述
我是 GraphQL 的新手。我在使用 express-graphql 服务器从 API 获取数组数据时遇到问题,我发现在某个地方很难解决。这是场景。
我有一个来自 REST API 的 GET 数据,它的响应类似于这样:
{
"id": 1,"name": "billy","foods": [
{
"food":{
"name":"crepes","taste": "crunchy"
}
},{
"food":{
"name":"noodle","taste":"spicy"
}
},]
}
在我的架构中,我成功地获得了 id
和 name
,我是这样实现的:
const FoodsType= new GraphQLObjectType({
name: 'foods',fields: () => ({
id:{ type: GraphQLInt },name:{ type: GraphQLString},foods: { type: GraphQLArray}
})
});
正如您在上面的代码中看到的,我无法获取包含数组数据的食品数据,因为没有像 GraphQLArray
这样的标量类型。
我的问题是我们如何获得包含多个 json 数据 foods
的 food
数据?
解决方法
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
}
}
}