【问题标题】:How to handle Union or Interface in graphQL mutations?如何处理 graphQL 突变中的 Union 或 Interface?
【发布时间】:2019-11-19 03:24:58
【问题描述】:

我得到了以下架构:

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!
}

等等updateBoatVehicleaddCarVehicleupdateCarVehicle。 但是如果我得到很多车型,或者可能是第三或第四个突变,恐怕很快就会变得很麻烦。

有什么推荐的方法来管理这个案例吗?

【问题讨论】:

    标签: graphql


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-10-20
      • 1970-01-01
      • 2018-05-21
      • 2020-09-02
      • 2020-02-16
      • 1970-01-01
      • 1970-01-01
      • 2020-04-11
      • 2019-02-21
      相关资源
      最近更新 更多