简体   繁体   English

GraphQL中“ schema” typedef的用途是什么?

[英]What is the use of `schema` typedef in GraphQL?

I'm getting started on GraphQL with Apollo + Express and I see that the example adds a schema name at the bottom of the typedefs: 我使用Apollo + Express开始使用GraphQL,我看到该示例在typedef的底部添加了一个schema名称:

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

schema {
  query: Query
}`];

And after defining the resolvers it generates the schema with makeExecutableSchema : 并且在定义了解析器之后,它使用makeExecutableSchema生成模式:

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

However if I remove the schema part of the typedefs I can still use my endpoint normally, eg: 但是,如果删除了typedef的schema部分,我仍然可以正常使用端点,例如:

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

returns: 收益:

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

But if I change the query part for something else, the server fails: 但是,如果我将查询部分更改为其他内容,则服务器将失败:

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

schema {
  testquery: Query
}`];

GraphQLError: Syntax Error: Unexpected Name "testquery" GraphQLError:语法错误:意外的名称“ testquery”

I have read through Apollo's tutorial pages and also the How To GraphQL tutorial for Node.js + GraphQL but can't find reference to that schema part. 我已经阅读了Apollo的教程页面以及Node.js + GraphQLHow to GraphQL教程,但是找不到对该schema部分的引用。

What is it used for? 这有什么用途?

About the schema 关于架构

A schema can have up to three root operation types but it requires only one. 模式最多可以具有三种根操作类型,但仅需要一种。 The query type must be present in every schema and needs to be an object type ( Spec ). 查询类型必须存在于每个模式中,并且必须是对象类型( Spec )。 This type is the root type when making queries to GraphQL. 对GraphQL进行查询时,此类型是根类型。 Furthermore there is a mutation root type that is used when making mutations. 此外,进行突变时会使用突变根类型。 The latest addition is the subscription type. 最新添加的是订阅类型。

About root types 关于根类型

Root types are simple object types. 根类型是简单的对象类型。 They can have fields and these fields are arguments. 它们可以具有字段,而这些字段是参数。 By default the query type is called Query , the mutation type is called Mutation and the subscription root type is called Subscription . 默认情况下,查询类型称为Query ,突变类型称为Mutation ,订阅根类型称为Subscription If you follow these standard names the schema specification can be omitted. 如果遵循这些标准名称,则可以省略schema规范。

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

Still you can name these types however you want. 您仍然可以根据需要命名这些类型。 To define which of your object types is a root type to enter the graph you have to use the schema definition. 要定义哪种对象类型是输入图的根类型,您必须使用模式定义。

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

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

The same thing can be done for mutation and subscription types. 对于突变和订阅类型,可以完成相同的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM