在输入可以采用不同类型的地方制作 Graphql 输入

Making Graphql input where input can take different types

我想创建变异 apis,其中输入可以是不同的类型,类似于我们在类型中拥有的接口。我知道我们不能在输入类型中有接口,我想知道我们如何在一个输入中支持多种输入类型。为了解释这个问题,我使用了一个虚拟示例:

input CreateCatInput{
  id: String
  name: String
}

input CreateDogInput{
  id: String
  name: String
  breed: String
}

input CreateElephantInput{
  id: String
  name: String
  weight: String
}

现在,如果我们要为它写 apis,我将不得不为每个类型写 api

createCat(input: CreateCatInput!)
createDog(input: CreateDogInput!)
createElephant(input: CreateElephantInput!)

我使用这种方法的问题是:

  1. 我还要写很多api,假设我支持20种 animal 那么我将不得不写 20 create apis。但我不喜欢用户看到这么多 api,我希望用户看到的 api 很少。
  2. 假设我们支持 20 种动物,用户如何知道所有动物都支持什么,他们必须在 API 资源管理器中查看我们支持的所有 api。

我正在寻找的解决方案是我只有一个 api :

  createAnimal(input: CreateAnimalInput!)

由于目前还没有接口支持,那么公司是如何实现可以是多种类型的输入的呢?如何定义输入,以便我只能在 api 中提供一个输入?

我读过这个suggestion,但是它涉及定义注释,我目前正在尝试。我想看看其他人是如何解决这个问题的。

编辑:看起来在这个主题上已经做了很多工作 https://github.com/graphql/graphql-spec/pull/733,该功能很快就会可用。

Input union type can solve your problem but unfortunately it is not supported now . However , the good news is that there is already a for this feature which means it is possible it will include in the next GraphQL specification release.

At this moment , I will model it using the nested input with an enum to differentiate which animal type the user is actually want to create. Somethings look like :

input CreateAnimalInput{
  id:   String
  name: String
  animalType :AnimalType!
  dogParam   : CreateDogInput
  elephantParam : CreateElephantInput
}

enum AnimalType{
  DOG
  ELEPHANT
}

input CreateDogInput{
  breed: String
}

input CreateElephantInput{
  weight: String
}

createAnimal(input: CreateAnimalInput!)

If an animalType is set to DOG , only values in the dogParam field will be considered and other animal parameter fields will be ignored.