【问题标题】:Dynamic type in GraphQLGraphQL 中的动态类型
【发布时间】:2020-08-26 14:23:50
【问题描述】:
const typeDef = `

  type User {
    id: ID!
    name: String!
    email: String!
  }
  type Post { 
    id: ID!
    title: String!
    content: String!
  }
  extend type Query {
    getDocuments(collection: String!): [User] || [Post]     // <<<<< Here!
  }   
`

是否可以将getDocuments 类型定义为[User][Post] 两者? 我有几个数据集合(用户、帖子、付款等...),我想定义一个 getter getDocuments 来获取数据以减少重复代码。

// like this

getDocuments(collection: 'User')
getDocuments(collection: 'Post')

【问题讨论】:

    标签: graphql react-apollo


    【解决方案1】:

    来自spec

    GraphQL 支持两种抽象类型:接口和联合。

    一个接口定义了一个字段列表;实现该接口的对象类型保证实现这些字段。每当类型系统声称它会返回一个接口时,它都会返回一个有效的实现类型。

    联合定义了可能的类型列表;与接口类似,只要类型系统声明将返回联合,就会返回其中一种可能的类型。

    所以你可以这样做:

    union Document = User | Post
    
    extend type Query {
      getDocuments(collection: String!): [Document]
    }
    

    如果类型共享一个或多个字段,您可以使用接口——否则,您必须使用联合。

    该字段的类型将在运行时根据您提供的resolveType 函数解析。有关如何为您的类型提供函数的更多详细信息,请参阅here

    最后,在查询字段时,您现在需要使用片段根据类型指定要请求的字段:

    getDocuments {
      ... on User {
        id
        name
      }
      ... on Post {
        id
        title
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-07
      • 2021-07-01
      • 2018-04-08
      • 2022-07-09
      • 2018-12-23
      • 2020-09-16
      相关资源
      最近更新 更多