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 }
A GraphQL fragment is a piece of logic that can be shared between multiple queries and mutations. Every fragment includes a subset of the fields that belong to its associated type. In the above example, the Person type must declare firstName and lastName fields for the NameParts fragment to be valid.
Hence, we can create two separate schemas, the Admin and Public schemas, and expose them under endpoints /graphql/admin and /graphql respectively.
GraphQL in Action MEAP V05 Inline fragments are, in a way, similar to anonymous functions that you can use without a name. They are just fragments without names and you can spread them inline where you define them.
The __typename field returns the object type's name as a String (e.g., Book or Author ). GraphQL clients use an object's __typename for many purposes, such as to determine which type was returned by a field that can return multiple types (i.e., a union or interface).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With