制作 Graphql 输入,其中输入可以采用不同类型

Dee*_*kar 3 graphql graphql-java graphql-schema

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

input CreateCatInput{
  id: String
  name: String
}

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

input CreateElephantInput{
  id: String
  name: String
  weight: String
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我们想为它编写 apis,我将不得不为每种类型编写 api

createCat(input: CreateCatInput!)
createDog(input: CreateDogInput!)
createElephant(input: CreateElephantInput!)
Run Code Online (Sandbox Code Playgroud)

我对这种方法的问题是:

  1. 我将不得不编写很多 api,假设如果我支持 20 种动物,那么我将不得不编写 20 个创建 api。但是我不喜欢为用户提供这么多的api,我希望用户应该看到很少的api。
  2. 假设我们支持 20 种动物,用户如何知道所有动物都支持什么,他们必须在 API Explorer 中看到我们支持的所有 api。

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

  createAnimal(input: CreateAnimalInput!)
Run Code Online (Sandbox Code Playgroud)

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

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

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

Ken*_*han 5

输入联合类型可以解决您的问题,但不幸的是现在不支持。然而,好消息是这个特性已经有一个RFC,这意味着它可能会包含在下一个 GraphQL 规范版本中。

此时,我将使用带有枚举的嵌套输入对其进行建模,以区分用户实际想要创建的动物类型。有些东西看起来像:

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!)
Run Code Online (Sandbox Code Playgroud)

如果 ananimalType设置为DOG,则仅dogParam考虑该字段中的值,而忽略其他动物参数字段。

  • 只是为了更新当前状态。oringal RFC 链接,链接回该线程,但实际链接是[此处](https://github.com/graphql/graphql-spec/issues/488)。然而,这已被“oneof”输入类型取代,可以在[此处](https://github.com/graphql/graphql-spec/pull/825)查看。 (3认同)