如何在 Graphql 中创建不同类型的列表
How to create a list of different types in Graph QL
我是 GraphQL 的新手,我正在尝试找出模式设计背后的最佳实践。为 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、品牌、型号)的每种类型的车辆,已经有一个模式和一个解析器:
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"
}
}
]
}
}
嗯,你可以使用继承。
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 不期望对象之间有一些共同的属性,因此保存的结构更大。
我是 GraphQL 的新手,我正在尝试找出模式设计背后的最佳实践。为 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、品牌、型号)的每种类型的车辆,已经有一个模式和一个解析器:
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"
}
}
]
}
}
嗯,你可以使用继承。
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 不期望对象之间有一些共同的属性,因此保存的结构更大。