在GraphQL中使用`schema` typedef有什么用?
我开始使用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 pages和How To GraphQL tutorial for Node.js + GraphQL但是找不到对schema
部分的引用。
它是干什么用的?
回答如下:关于架构
模式最多可以有三种根操作类型,但只需要一种。查询类型必须存在于每个模式中,并且需要是对象类型(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
}
对于变异和订阅类型,可以做同样的事情。