GraphQL Schema中如何在多个类型间实现公共字段片段复用
错误原因
你遇到的报错是因为GraphQL片段(Fragment)是查询侧的语法,仅用于复用查询请求的字段,不能用于服务端类型定义(SDL)的字段复用,你在type定义里写的...CoreCustomerFragment是无效语法,解析器识别不到任何有效字段,所以抛出"Customer must define one or more fields"错误。
正确复用方案
方案1:使用GraphQL Interface(接口,原生标准支持,无需额外工具)
这是GraphQL规范原生支持的类型字段复用方式,适合所有场景:
# 1. 先定义包含公共字段的接口 interface CoreCustomer { _id: ObjectID first_name: String last_name: String mobile: String national_code: NonNegativeInt } # 2. 两个业务类型都实现该接口 type Customer implements CoreCustomer { # 接口要求的公共字段 _id: ObjectID first_name: String last_name: String mobile: String national_code: NonNegativeInt # 自有字段 field1: String } type CustomerInformation implements CoreCustomer { # 接口要求的公共字段 _id: ObjectID first_name: String last_name: String mobile: String national_code: NonNegativeInt # 自有字段 field2: String }
如果觉得重复写公共字段麻烦,可以搭配Node.js做SDL模板拼接,把公共字段提取成字符串常量复用:
// 提取公共字段字符串 const coreCustomerFields = ` _id: ObjectID first_name: String last_name: String mobile: String national_code: NonNegativeInt ` // 拼接生成完整SDL const typeDefs = ` type Customer { ${coreCustomerFields} field1: String } type CustomerInformation { ${coreCustomerFields} field2: String } `
方案2:代码式类型定义复用(适合用GraphQL.js原生API定义类型的场景)
如果你不用SDL,而是用JS对象方式定义GraphQL类型,可以直接把公共字段提取为对象复用:
// 公共字段对象 const coreCustomerFields = { _id: { type: GraphQLObjectID }, first_name: { type: GraphQLString }, last_name: { type: GraphQLString }, mobile: { type: GraphQLString }, national_code: { type: GraphQLNonNegativeInt } } // 定义类型时扩展公共字段 const CustomerType = new GraphQLObjectType({ name: 'Customer', fields: { ...coreCustomerFields, field1: { type: GraphQLString } } }) const CustomerInformationType = new GraphQLObjectType({ name: 'CustomerInformation', fields: { ...coreCustomerFields, field2: { type: GraphQLString } } })
内容的提问来源于stack exchange,提问作者Web Jigooli
相关产品推荐
相关产品推荐

