来自嵌套 JSON 列表的架构 [英] Schema from nested JSON list
问题描述
我有一个捕获一对多关系的 JSON 列表.
I have a JSON list which captures one to many relationships.
例如,School 可以有多个 Class 对象,Class 可以有多个 Student 对象,但是 Student 只属于一个 Class 和一个 School:
For example, School can have multiple Class objects and Class can have multiple Student objects, but Student only belongs to one Class and one School:
{
"School": [ {
"id": 1,
"name": "Grad School",
"Class": [ {
"name": 101,
"Student": [ {
"name": 501,
"propertyA": "test"
}]
}]
}]
}
我正在尝试将此 JSON 示例转换为适当的架构,但嵌套导致了问题.Apollo 似乎能够提供帮助,但下面的示例不是很具有描述性:https://launchpad.graphql.com/4nqqqmr19
I am trying to convert this JSON example into an appropriate schema but the nesting is causing issues. Apollo appears to be able to help but the example below isn't very descriptive: https://launchpad.graphql.com/4nqqqmr19
我正在寻找有关如何处理这种情况的建议,无论是通过 JSON 模式转换器(处理嵌套情况)还是其他方式.
I'm looking for suggestions on how to handle this situation, whether that be through a JSON schema converter (which handles nested situations) or other.
推荐答案
我认为您的问题并不是真正的架构,这在我看来很简单:
I think you issue is not really the schema, which to me looks straightforward:
您有这些类型(所有虚拟代码,因为您没有指定要提供 GraphQL-Api 的语言/框架):
You have these types (everything dummy code as you have not specified in what language/framework you want to provide the GraphQL-Api):
SchoolType
id ID
name String
classes [Class]
students [Students]
ClassType
id ID
name String
school School
students [Student]
StudentType
id ID
name String
class Class
school School
然后我们需要一个入口点
Then we need an entry point
classQueryType
name "school"
argument :id, ID
resolve do
schools.where(id: argument["id"])
所以我们有了架构.更大的工作可能是让不同的类型以上述类型工作的方式访问 JSON 模式.
So we have the schema. The bigger work is probably to get the different types to access the JSON Schema in a way that the types above work.
比如说,我们以某种方式读取了 JSON 数据,以及您拥有的结构.
So let's say, we read the JSON data somehow, with the structure you have.
const DATA = JSON.parse("your-example.json")
我们需要将其转换为不同的对象集合,以便我们可以动态查询它们:
We need to convert this into different collections of objects, so we can query them dynamically:
schools = []
classes = []
people = []
def build_schools(data)
data.schools.for_each do |school|
schools.push(
name: school.name,
id: school.id,
classes: build_classes(school)
)
end
end
def build_classes(school)
ids = []
school.classes.for_each do |class|
ids.push(class.id)
classes.push(
id: class.id
name: class.name
school_id: school.id # you create your own references, to associate these objects
students: build_students(class)
)
end
return ids
end
...
但是你仍然需要把它和你的类型系统联系起来.这意味着编写您的解析器:
But then you still need to hook this up, with your type system. Which means to write your resolvers:
例如在 StudentType 上
For example on the StudentType
StudentType
id ID
name String
class Class
school School
resolve(object) ->
school_id = students.where(id: object.id).class_id.school_id
schools.where(id: school_id)
这篇关于来自嵌套 JSON 列表的架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!