graphql - 如何处理 graphQL 突变中的 Union 或 Interface?
问题描述
我得到以下架构:
type Vehicle {
id: ID!
name: String!
color: String!
}
input AddVehicle {
name: String!
color: String!
}
input UpdateVehicle {
id: ID!
name: String!
}
现在我想根据车辆型号为我的车辆添加一些属性,例如
type CarProperties {
wheelSize: Int!
doors: Int!
}
type BoatProperties {
length: Int!
}
union VehicleProperties = CarProperties | BoatProperties
type Vehicle {
[ ... ]
properties: vehicleProperties!
}
因此,编写查询非常简单,但是在进行突变时我正在苦苦挣扎......
AFAIK graphQL 输入没有实现联合或接口(这里有一个相关线程https://github.com/graphql/graphql-spec/issues/488)
所以我在这里看到的解决方法是复制我的输入,比如:
input addBoatVehicle {
name: String!
color: String!
properties: BoatProperties!
}
依此类推,updateBoatVehicle
, addCarVehicle
, updateCarVehicle
. 但如果我得到很多车型,或者可能是第三或第四个突变,恐怕很快就会变得很麻烦。
有什么推荐的方法来管理这种情况吗?
解决方案
创建单独的突变是正确的解决方案。您可以通过使您的突变非常轻量级并将这些项目的处理重构为一个单独的函数来减轻一些痛苦。
function addVehicle(input) {
// disambiguate the input type
}
function updateVehicle(input) {
// dismabiguate the input type, preferably in its own refactor function so
// it can be used above too!
}
const resolvers = {
Mutation: {
addBoat: (parent, boatInput) => { return addVehicle(boatInput) },
addCar: (parent, carInput) => { return addVehicle(carInput) },
updateBoat: (parent, boatInput) => { return updateVehicle(boatInput) },
updateCar: (parent, carInput) => { return updateVehicle(carInput) },
}
}
推荐阅读
- r - 如何融化数据框中的列表列
- go - 解析文件中的数据时地图大小不同的地图
- javascript - 桌面版 Chrome 支持的最大图像尺寸是多少?
- java - 为什么我的 2D 阵列克隆不止一次?
- ruby - 如何访问在 secret.yml 中定义并在其他 Ruby 脚本中需要的变量
- ruby - Vagrantfile:如何传递带有未转义美元符号的主机环境变量?
- laravel - Laravel 从表单获取值到日期('request->date')
- c# - 具有单个通用参数和多个约束的最小起订量方法
- python - 如何从 pandas DataFrames 列表创建一个 csv 文件?
- wordpress - 如何在 WordPress 中访问成员函数到模板文件?