【问题标题】:Graphql - How to include schema from other typesGraphql - 如何包含其他类型的模式
【发布时间】:2022-02-02 16:32:37
【问题描述】:

假设我有以下类型:

type Foo {
  id: ID!
  field1: String
}

现在,我想定义另一种类型,包括早期的类型。像这样的:

type Bar {
  ...Foo,
  field2: String
}

如何在 graphql 中实现上述目标?我想基本上是先创建一个类型,然后将该类型包含在其他类型的定义中,这样我就不必多次键入所有属性。

我正在使用 Amplify / AWS Appsync 所以如果有任何我可以使用的特殊指令也会有所帮助

【问题讨论】:

    标签: graphql aws-amplify aws-appsync


    【解决方案1】:

    GraphQL 对此有 interfaces 的概念。 Appsync,AWS 的 GraphQL 实现,supports interfaces

    [编辑:] GraphQL 不支持接口的“...spread”语法。字段是明确定义的。 Spread 语法在 GraphQL 中确实存在,但以 Fragments 的形式出现,可重复使用的字段单元可减少查询中的重复。

    interface Character {
      id: ID!
      name: String!
      friends: [Character]
      appearsIn: [Episode]!
    }
    
    type Human implements Character {
      id: ID!
      name: String!
      friends: [Character]
      appearsIn: [Episode]!
      starships: [Starship]
      totalCredits: Int
    }
    
    type Droid implements Character {
      id: ID!
      name: String!
      friends: [Character]
      appearsIn: [Episode]!
      primaryFunction: String
    }
    

    自动创建 AppSync 架构、解析器和数据源的 Amplify 显然是一个更困难的故事。 amplify-cli repo 有一个开放的功能请求,Does the GraphQL Transformer support interfaces?。我不是 Amplify 专家,但快速浏览 loooong 功能请求评论线程表明 Amplify 的答案是“不是开箱即用的”,但 “可能适用于狭义情况或高级定制”

    【讨论】:

    • 这需要我在每个实现接口的类型中重新定义属性。我正在考虑不要再次输入相同的属性 - 只需“导入”它,如果这有意义的话
    • 不,GraphQL 规范不支持类型定义中的语法。字段在模式中明确定义。 "...spread" 语法确实出现在 GraphQL 中,但以 Fragments 的形式出现,可重复使用的字段单元用于减少 查询 中的重复。
    • 我明白了。您可以使用上述内容编辑您的答案吗?我会将其标记为已接受
    • @callmekatootie 已编辑。
    猜你喜欢
    • 1970-01-01
    • 2016-11-29
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 2017-01-21
    • 1970-01-01
    相关资源
    最近更新 更多