简体   繁体   中英

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:

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

schema {
  query: Query
}`];

And after defining the resolvers it generates the schema with makeExecutableSchema :

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

However if I remove the schema part of the typedefs I can still use my endpoint normally, eg:

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"

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.

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 ). This type is the root type when making queries to 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 . If you follow these standard names the schema specification can be omitted.

# 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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