【问题标题】:Graphql only allows one root query?Graphql 只允许一个根查询?
【发布时间】:2020-03-10 11:40:53
【问题描述】:

正如blog 所说

一个要求是必须只有一个根查询,并且 ...

考虑架构

type Post {
    id: ID!
    title: String!
    text: String!
    category: String
    author: Author!
}
 
type Author {
    id: ID!
    name: String!
    thumbnail: String
    posts: [Post]!
}

# The Root Query for the application
type Query {
    recentPosts(count: Int, offset: Int): [Post]!
}

这是否意味着我不能像下面这样声明另一个根查询?除了根查询还有其他查询类型吗?

# Another  query
type Query {
    getPost(id: Int): [Post]!
}

# Another  query
type Query {
    getAuthor(id: Int): [Author]!
}

【问题讨论】:

  • 它与Java有什么关系?而且链接坏了

标签: graphql


【解决方案1】:

在 GraphQL 中,共有三个操作:querymutationsubscription。这些操作中的每一个都有一个与之关联的类型,尽管您只需要为query 提供一个类型——其他两个是可选的。我们将这些类型称为root operation types

我们为这样的模式指定根操作类型:

schema {
  query: Query
  mutation: Mutation
}

您可以将查询类型命名为任何名称(QueryRootQueryFooBar 等)。但是,如果您将其命名为Query,则可以省略上述步骤(GraphQL 将简单地假设三种根操作类型将命名为QueryMutationSubscription)。

我们的查询类型必须是object type,所以我们使用type 关键字来定义它并为其提供至少一个字段:

type Query {
  getPost(id: Int): Post!
}

type Post {
  id: ID!
  title: String!
  text: String!
}

有了这个模式,我们现在可以编写一个查询。我们没有指定MutationSubscription 类型,所以我们只能执行一个操作——query

query {
  getPost(id: 5) {
    id
    title
  }
}

正如我们所见,我们将 Query 称为 root 操作类型,因为它代表 root 或我们模式其余部分的条目。您发送到服务器的每个可执行文档都必须从该根目录开始,尽管类型会因操作(查询、变异或订阅)而异。

Query 是一个对象类型,这意味着我们可以向它添加额外的字段:

type Query {
  getPost(id: Int): Post
  getAuthor(id: Int): Author
}

type Post {
  id: ID!
  title: String!
  text: String!
}

type Author {
  id: ID!
  name: String!
}

现在我们可以编写不同的查询:

query {
  getAuthor(id: 7){
    id
    name
  }
}

甚至请求两个字段:

query {
  getPost(id: 3) {
    id
    title
  }
  getAuthor(id: 11){
    id
    name
  }
}

您不会像问题中显示的那样定义 Query 两次 - 您只需添加额外的字段,如上所示。

如需更多信息,请参阅the specofficial tutorial

【讨论】:

【解决方案2】:

是的,在 GraphQL 中只有一个根查询。但是,您可以通过提供“存根”字段 + 解析器在根查询上“命名空间”查询,如下所示。

type Booking {
    _id: ID!
    event: Event!
    user: User!
    createdAt: String!
    updatedAt: String!
}

type Event {
    _id: ID!
    title: String!
    description: String!
    date: String!
}

type RootQuery {
    events: [Event!]!
    bookings: [Booking!]!
}

schema {
    query: RootQuery
}

【讨论】:

  • 您能否详细说明You can however "namespace" your queries on the root Query by providing a "stub" field + resolver, like shown below. ?另外,如果我只能声明一个根查询说POST,但我只想得到Author,我怎样才能得到它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
  • 2020-07-02
  • 2012-07-14
  • 2020-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多