Interface 如何确定查询返回给GraphQL接口类型的显式类型?
假设我们有一个使用继承的GraphQL模式:Interface 如何确定查询返回给GraphQL接口类型的显式类型?,interface,graphql,Interface,Graphql,假设我们有一个使用继承的GraphQL模式: Query { maintenanceEvents: [MaintenanceEvent]! } interface MaintenaceEvent { time: DateTime } type OilChange implements MaintenanceEvent { time: DateTime oilType: OilType } type TireRotation implements MaintenanceEve
Query {
maintenanceEvents: [MaintenanceEvent]!
}
interface MaintenaceEvent {
time: DateTime
}
type OilChange implements MaintenanceEvent {
time: DateTime
oilType: OilType
}
type TireRotation implements MaintenanceEvent {
time: DateTime
pattern: RotationPattern
}
... more types
并说客户端将显示时间轴上发生的事件类型的摘要。问题是(据我所知),客户机无法直接确定从服务器接收到的阵列中每个事件的类型
我提出了一些选择:
enum MaintenanceEventType {
OIL_CHANGE
TIRE_ROTATION
... more types
}
interface MaintenanceEvent {
time: DateTime
type: MaintenanceEventType
}
type OilChange implements MaintenanceEvent {
time: DateTime
type: MaintenanceEventType
oilType: OilType
}
...etc.
这是我想到的最好的选择,但有些地方我不喜欢。要保持同步的维护事件类型有两个列表:枚举和接口集。此外,对于给定类型,发送始终相同的字段似乎是多余的是否有一个已建立的模式,或者GraphQL规范的一部分来处理这个问题?这不是GraphQL接口的一个好应用吗?您应该使用
\uu typename
字段。从:
GraphQL支持通过meta-field\uuuTypeName:String在查询中的任意点进行类型名内省!查询任何对象、接口或联合时。它返回当前正在查询的对象类型的名称
在查询接口或联合类型以确定已返回的可能类型的实际类型时,最常使用这种方法
此字段是隐式的,不会以任何定义的类型出现在“字段”列表中
您的查询类似于:
query {
maintenanceEvents {
__typename
time
... on OilChange {
oilType
}
... on TireRotation {
pattern
}
}
}
请注意,如果您使用Apollo客户端,\uuu typename
字段将自动添加到您的查询中——在这种情况下,无需自己显式添加它