在多个类型上使用GraphQL片段
如果在我的GraphQL模式中有一组对多个类型通用的字段,有没有类似的方法在多个类型上使用GraphQL片段,graphql,apollo,Graphql,Apollo,如果在我的GraphQL模式中有一组对多个类型通用的字段,有没有类似的方法 type Address { line1: String city: String state: String zip: String } fragment NameAndAddress on Person, Business { name: String address: Address } type Business { ...NameAndAddress hours: St
type Address {
line1: String
city: String
state: String
zip: String
}
fragment NameAndAddress on Person, Business {
name: String
address: Address
}
type Business {
...NameAndAddress
hours: String
}
type Customer {
...NameAndAddress
customerSince: Date
}
片段仅在发出请求时在客户端使用——它们不能在模式中使用。GraphQL不支持类型继承或任何其他机制,以减少为不同类型写出相同字段的冗余 如果您使用的是阿波罗服务器,则构成模式的类型定义只是一个字符串,因此您可以通过模板文本实现所需的功能:
const nameAndAddress = `
name: String
address: Address
`
const typeDefs = `
type Business {
${nameAndAddress}
hours: String
}
type Customer {
${nameAndAddress}
customerSince: Date
}
`
或者,还有一些库,比如,允许您使用类型继承。不知道在这个问题时间它是否不可用,但我想应该适合您的需要。我觉得奇怪的是,GraphQL中不支持这一点。在这种情况下,类型及其相应的输入具有许多共享字段。使用字符串插值意味着我不能只使用普通的
.graphql
文件。这也意味着另一种语言不能使用相同的.graphql
文件。看起来GraphQL中应该支持这一点。奇怪的是没有类型继承。