[英]GraphQL Schema for Nested JSON?
I am trying to use GraphQL to deal with some JSON data. 我正在尝试使用GraphQL来处理一些JSON数据。 I can retrieve fields from the top level no problem. 我可以从顶层检索字段没问题。 I can associate separate JSON objects also no problem. 我可以关联单独的JSON对象也没问题。 My problems are occurring trying to get at data one level down. 我的问题正在发生,试图将数据降低一级。 So, I have defined a type in my schema for staff. 所以,我已经在我的架构中为员工定义了一个类型。 The json looks like this: json看起来像这样:
"staff": [
{
"id": 123,
"name": "fred",
"role" : "designer",
"address": {
"street": "main street",
"town": "Springfield"
}
},
...
]
and the corresponding type in the schema looks like this so far: 到目前为止,模式中的相应类型如下所示:
const StaffType = new GraphQLObjectType({
name: 'Staff',
fields: {
id: {type: GraphQLInt},
name: {type: GraphQLString},
role: {type: GraphQLString}
}
})
This works fine as far as retrieving the id, name and role goes. 就检索id,名称和角色而言,这样可以正常工作。 My question is how can I extend StaffType
to also retrieve street
and town
from the address
field in the original JSON? 我的问题是如何扩展StaffType
以从原始JSON中的address
字段检索street
和town
?
Thanks 谢谢
Ok, I figured it out. 好的,我明白了。 I was getting hung up on the idea of a distinct Type in the schema having to refer to a separate piece of JSON whereas, in fact, I can define an AddressType in the schema to refer to the nested data and then include it in the StaffType without having to write a resolve function. 我对模式中的不同类型的想法感到困惑,不得不引用一个单独的JSON,而实际上,我可以在模式中定义一个AddressType来引用嵌套数据,然后将它包含在StaffType中无需编写解析功能。
[edit to add example] [编辑添加示例]
const StaffType = new GraphQLObjectType({
name: 'Staff',
fields: {
id: {type: GraphQLInt},
name: {type: GraphQLString},
role: {type: GraphQLString},
address: {type: AddressType}
}
})
const AddressType = new GraphQLObjectType({
name: 'Address',
fields: {
street: {type: GraphQLString},
town: {type: GraphQLString}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.