【问题标题】:What is the use of `schema` typedef in GraphQL?GraphQL 中的 `schema` typedef 有什么用?
【发布时间】:2018-06-06 22:03:27
【问题描述】:

我正在使用 Apollo + Express 开始使用 GraphQL,我看到 the example 在 typedef 的底部添加了一个 schema 名称:

let typeDefs = [`
type Query {
  hello: String
}

schema {
  query: Query
}`];

在定义解析器后,它会生成带有makeExecutableSchema 的架构:

let schema = makeExecutableSchema({typeDefs, resolvers});

但是,如果我删除 typedef 的 schema 部分,我仍然可以正常使用我的端点,例如:

http://localhost:3000/graphql/?query={hello}

返回:

{"data":{"hello":"world"}}

但如果我将查询部分更改为其他内容,服务器将失败:

let typeDefs = [`
type Query {
  hello: String
}

schema {
  testquery: Query
}`];

GraphQLError:语法错误:意外名称“testquery”

我已通读Apollo's tutorial pagesHow To GraphQL tutorial for Node.js + GraphQL,但找不到对schema 部分的引用。

它是做什么用的?

【问题讨论】:

标签: node.js graphql apollo


【解决方案1】:

关于架构

一个模式最多可以有三种根操作类型,但它只需要一种。查询类型必须存在于每个模式中,并且必须是对象类型 (Spec)。此类型是对 GraphQL 进行查询时的根类型。此外,在进行突变时会使用一种突变根类型。最新添加的是订阅类型。

关于根类型

根类型是简单的对象类型。它们可以有字段,这些字段是参数。默认情况下,查询类型称为Query,变异类型称为Mutation,订阅根类型称为Subscription。如果您遵循这些标准名称,则可以省略 schema 规范。

# Doesn't need further specification, Query is the default name
type Query {
  # ...
}

您仍然可以随意命名这些类型。要定义哪些对象类型是要进入图表的根类型,您必须使用模式定义。

# Non standard query type name
type MyQuery {
  # ...
}

schema {
  # Needs to be defined in the schema declaration
  query: MyQuery
}

对于变异和订阅类型可以做同样的事情。

【讨论】:

    猜你喜欢
    • 2011-02-03
    • 2017-09-25
    • 2018-09-07
    • 2016-06-04
    • 2013-01-25
    • 2019-11-16
    • 2018-08-09
    • 2021-07-23
    • 2011-06-18
    相关资源
    最近更新 更多