Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using GraphQL Fragment on multiple types

Tags:

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 } 
like image 587
Good Idea Avatar asked Feb 23 '18 02:02

Good Idea


People also ask

How do Fragments work in GraphQL?

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.

Can GraphQL have multiple schemas?

Hence, we can create two separate schemas, the Admin and Public schemas, and expose them under endpoints /graphql/admin and /graphql respectively.

What is inline fragment in GraphQL?

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.

What is __ Typename in GraphQL?

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).


2 Answers

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.

like image 132
Daniel Rearden Avatar answered Sep 21 '22 03:09

Daniel Rearden


Don't know if it was not available at this question time, but I guess interfaces should fit your needs

like image 44
aleclofabbro Avatar answered Sep 18 '22 03:09

aleclofabbro