如何处理graphQL中的联合或接口?
我得到了以下模式:如何处理graphQL中的联合或接口?,graphql,Graphql,我得到了以下模式: 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
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输入不实现联合或接口(这里有一个相关线程)
因此,我在这里看到的解决方法是复制我的输入,如:
input addBoatVehicle {
name: String!
color: String!
properties: BoatProperties!
}
依此类推,UpdateBatVehicle
,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) },
}
}
创建单独的突变是正确的解决方案。您可以通过使您的代码变得极其轻量级,并将这些项目的处理重构为一个单独的函数来减轻一些痛苦
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) },
}
}