如何解决如何从 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"
}
},]
}
在我的架构中,我成功地获得了 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
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。