如果我的GraphQL架构中有多个类型共有的字段集,有没有办法做这样的事情?
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
}
答案 0 :(得分:7)
片段仅在发出请求时在客户端使用 - 它们不能在架构中使用。 GraphQL不支持类型继承或任何其他机制,可以减少必须为不同类型写出相同字段的冗余。
如果您使用apollo-server
,构成架构的类型定义只是一个字符串,因此您可以通过模板文字实现您正在寻找的功能:
const nameAndAddress = `
name: String
address: Address
`
const typeDefs = `
type Business {
${nameAndAddress}
hours: String
}
type Customer {
${nameAndAddress}
customerSince: Date
}
`
或者,有一些库,如graphql-s2s,允许您使用类型继承。
答案 1 :(得分:0)
不知道在这个问题时间是否不可用,但是我猜interfaces应该符合您的需求