GraphQL 中的动态类型

Dynamic type in GraphQL

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')

来自spec

GraphQL supports two abstract types: interfaces and unions.

An Interface defines a list of fields; Object types that implement that interface are guaranteed to implement those fields. Whenever the type system claims it will return an interface, it will return a valid implementing type.

A Union defines a list of possible types; similar to interfaces, whenever the type system claims a union will be returned, one of the possible types will be returned.

所以你可以这样做:

union Document = User | Post

extend type Query {
  getDocuments(collection: String!): [Document]
}

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

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

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

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