【问题标题】:How to create a list of different types in Graph QL如何在 Graphql 中创建不同类型的列表
【发布时间】:2017-12-01 03:52:39
【问题描述】:

我是 GraphQL 的新手,我正在尝试找出 Schema 设计背后的最佳实践。为 GraphQL 设计模式和连接感觉有点像设计关系数据库,但我不确定所有的最佳实践。在 GraphQL 中,您将如何实现以下解决方案:

假设您有一份车辆清单:

1. Honda Accord
2. Ford Focus
3. Ducati Monster
4. Cessna 152
5. Santa Cruz Nomad

这些车辆中的每一种都属于不同的类型:

1. Honda Accord (car)
2. Ford Focus (car)
3. Ducati Monster (motorcycle)
4. Cessna 152 (airplane)
5. Santa Cruz Nomad (bicycle)

您已经拥有每种类型的架构

对于实现相同接口(id、make、model)的每种类型的车辆,已经有一个模式和一个解析器:

 Car {
    id,
    make
    model
    ...
 }

 MotorCycle {
    id
    make
    model
    ...
 }

 AirPlane {
    id,
    make
    model
    ...
 }

 Bicycle {
    id
    make
    model
    ...
 }

你将如何实现车库?

创建车库类型的最佳方法是什么?该车库类型可用于访问车库中可能找到的不同车辆类型的列表,即使每辆车都有自己的架构?

我不确定这是否可能,或者如何正确实施,但我想做的是:

{
    garage(id: "cGVvcGx10jE=") {
        location
        vehicleConnection {
            edges {
                node {
                    make
                    model
                }
            }
        }
    }
}

 {
     "data": {
       "garage": {
         "location": "Sunnyvale",
         "vehicleConection": {
             "edges": [
               {
                 "node": {
                     "make": "Honda",
                     "model": "Accord"
                 }
               },
               {
                 "node": {
                     "make": "Ford",
                     "model": "Focus"
                 }
               },                         {
                 "node": {
                     "make": "Ducati",
                     "model": "Monster"
                 }
               },
               {
                 "node": {
                     "make": "Cessna",
                     "model": "152"
                 }
               },
               {
                 "node": {
                     "make": "Santa Cruz",
                     "model": "Nomad"
                 }
               }             
    ]
  }
}

【问题讨论】:

    标签: graph-databases graphql


    【解决方案1】:

    嗯,你可以使用继承。

    interface Vehicle {
        id: ID!,
        make: String,
        model: String
    }
    
    type Car implements Vehicle {
        ...
    }
    
    type MotoCycle implements Vehicle {
        ...
    }
    
    // and now you can connect Garage to Vehicle
    

    http://graphql.org/learn/schema/#interfaces

    其他可能性:联合类型http://graphql.org/learn/schema/#union-types

    它们大致相同,但由于 union 不期望对象之间有一些共同的属性,所以保存的结构更大。

    【讨论】:

    • 我已经创建了车辆界面......它是 UNION TYPES......这正是我正在寻找的。谢谢!
    猜你喜欢
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多