The extend
keyword is great if you have a base schema and want to build two or more usable schemas based on it. You can, for example, define a root Query
type with queries shared by all schemas, and then extend it within each individual schema to add queries specific to that schema. It can also be used to modularize a schema. However, it's only a mechanism to add functionality to existing types -- it can't be used to create new types.
GraphQL does not inherently support inheritance. There is no syntax that would help you avoid duplication of fields across multiple types.
You can utilize string interpolation to avoid typing out the same fields again and again:
const sharedFields = `
foo: String
bar: String
`
const typeDefs = `
type A {
${sharedFields}
}
type B {
${sharedFields}
}
`
Barring that, you can also utilize a library like graphql-s2s which allows you to utilize inheritance and generic types. Schemas generated this way still have to be compiled to valid SDL though -- at best, libraries like graphql-s2s
just offer some syntactic sugar and a better DX.
Lastly, you can restructure your types to avoid the field duplication altogether at the cost of a more structured response. For example, instead of doing this:
type A {
a: Int
foo: String
bar: String
}
type B {
b: Int
foo: String
bar: String
}
you can do this:
type X {
foo: String
bar: String
aOrB: AOrB
}
union AOrB = A | B
type A {
a: Int
}
type B {
b: Int
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…