GraphQL中type Query与extend type Query的区别是什么?
GraphQL中
type Query与extend type Query的区别 核心区别
type Query:用来定义根查询类型的基础结构,是整个GraphQL schema里查询根类型的起点。一个合法的schema里,只能有一个不带extend的基础type Query定义,不能重复写。extend type Query:专门用来给已经定义好的Query根类型追加字段,适合拆分schema、按业务模块开发的场景——比如不同模块的查询字段写在不同文件里,用这个语法就能把新字段合并到根查询里。
示例说明
场景1:单文件写完整schema
如果你的schema都放在一个文件里,直接用type Query把所有查询字段写完就行:
# 先定义产品类型 type Product { id: String! name: String! price: Float! } # 定义根查询,包含所有查询字段 type Query { # 根据ID查单个产品 product(id: String!): Product # 查所有产品 allProducts: [Product!]! }
场景2:模块化拆分schema
当项目变大,把设备相关的逻辑拆到单独文件时,就需要用extend type Query来追加新查询:
主schema文件(base.graphql)
type Product { id: String! name: String! price: Float! } # 先搭好根查询的基础架子 type Query { product(id: String!): Product }
设备模块文件(device.graphql)
# 定义设备详情类型 type DeviceDetail { devId: String! model: String! status: String! } # 给已有的根查询加新的查询字段 extend type Query { DeviceDetail(devId: String!): DeviceDetail }
最终合并后的schema效果等同于:
type Product { id: String! name: String! price: Float! } type DeviceDetail { devId: String! model: String! status: String! } type Query { product(id: String!): Product DeviceDetail(devId: String!): DeviceDetail }
必须注意的点
- 一个schema里只能有一个基础的
type Query,要是重复写不带extend的type Query,直接会报错。 extend type Query可以用多次,每次都能加新字段,团队协作拆分模块时特别好用。
内容的提问来源于stack exchange,提问作者cbot
相关产品推荐
相关产品推荐

