首页 > 解决方案 > 如何处理 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. 但如果我得到很多车型,或者可能是第三或第四个突变,恐怕很快就会变得很麻烦。

有什么推荐的方法来管理这种情况吗?

标签: graphql

解决方案


创建单独的突变是正确的解决方案。您可以通过使您的突变非常轻量级并将这些项目的处理重构为一个单独的函数来减轻一些痛苦。

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) },
  }
}

推荐阅读