【问题标题】:Schema from nested JSON list来自嵌套 JSON 列表的架构
【发布时间】:2018-10-30 14:53:18
【问题描述】:

我有一个捕获一对多关系的 JSON 列表。

例如,School 可以有多个 Class 对象,Class 可以有多个 Student 对象,但 Student 只属于一个 Class 和一个 School:

{
  "School": [ {
    "id": 1,
    "name": "Grad School",
    "Class": [ {
         "name": 101,
         "Student": [ {
              "name": 501,
              "propertyA": "test"
         }]
     }]
  }]
}

我正在尝试将此 JSON 示例转换为适当的架构,但嵌套会导致问题。 Apollo 似乎可以提供帮助,但下面的示例描述性不强: https://launchpad.graphql.com/4nqqqmr19

我正在寻找有关如何处理这种情况的建议,无论是通过 JSON 模式转换器(处理嵌套情况)还是其他方式。

【问题讨论】:

  • 我是否理解正确,您有 JSON 数据源,您自己没有数据库访问权限?
  • 希望我的回答能给你指明方向。

标签: json graphql apollo


【解决方案1】:

我认为你的问题并不是真正的架构,在我看来这很简单:

您有这些类型(所有虚拟代码,因为您没有指定要以哪种语言/框架提供 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

那么我们需要一个入口点

classQueryType
  name "school"
  argument :id, ID
  resolve do
    schools.where(id: argument["id"])

所以我们有了架构。更大的工作可能是让不同类型以上述类型工作的方式访问 JSON Schema。

假设我们以某种方式读取 JSON 数据,使用您拥有的结构。

 const DATA = JSON.parse("your-example.json")

我们需要把它转换成不同的对象集合,这样我们就可以动态地查询它们:

 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

 ...

但是您仍然需要将其与您的类型系统挂钩。这意味着编写您的解析器:

以 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)

【讨论】:

  • 啊,谢谢你的详细信息。我已经在 Neo4J 中有对象集合,这是我无法弄清楚的解析器。
  • 我计划使用的工作流程是 Neo4J -> GraphQL / Apollo -> React。我是否正确地说您提供的解析器方法可以在 Apollo 启动板中使用?
猜你喜欢
  • 2020-09-07
  • 2015-08-26
  • 1970-01-01
  • 2012-04-14
  • 2020-12-03
  • 1970-01-01
  • 2016-03-21
  • 2019-05-12
  • 1970-01-01
相关资源
最近更新 更多