问题描述
如果我的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 }
推荐答案
片段仅在提出请求时在客户端上使用 - 无法在您的模式中使用它们. GraphQl不支持类型的继承或任何其他将减少必须为不同类型写出相同字段的冗余的机制.
如果您正在使用apollo-server,则组成模式的类型定义只是一个字符串,因此您可以通过模板文字实现您要查找的功能:
const nameAndAddress = ` name: String address: Address ` const typeDefs = ` type Business { ${nameAndAddress} hours: String } type Customer { ${nameAndAddress} customerSince: Date } `
另外,还有库,例如 graphqlql-s2s 键入继承.
其他推荐答案
不知道在这个问题时是否不可用,但是我猜接口应该适合您的需求
问题描述
If I have a set of field that is common to multiple types in my GraphQL schema, is there a way to do something like this?
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 }
推荐答案
Fragments are only used on the client-side when making requests -- they can't be used inside your schema. GraphQL does not support type inheritance or any other mechanism that would reduce the redundancy of having to write out the same fields for different types.
If you're using apollo-server, the type definitions that make up your schema are just a string, so you can implement the functionality you're looking for through template literals:
const nameAndAddress = ` name: String address: Address ` const typeDefs = ` type Business { ${nameAndAddress} hours: String } type Customer { ${nameAndAddress} customerSince: Date } `
Alternatively, there are libraries out there, like graphql-s2s, that allow you to use type inheritance.
其他推荐答案
Don't know if it was not available at this question time, but I guess interfaces should fit your needs