Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add graphQL fragment to schema, and have available for all queries

Tags:

The following executes correctly in graphiQL

fragment BookGridFields on Book {
  _id
  title
}

{
  allBooks {
    ...BookGridFields
  }
}

My question is, it possible to specify the fragment right in my schema, right below where my Book type is defined, like so

type Book {
  _id: String
  title: String
  pages: Int
  weight: Float
  authors: [Author]
}

fragment BookGridFields on Book {
  _id
  title
}

So that I could just run queries like this

{
  allBooks {
    ...BookGridFields
  }
}

without needing to define the fragment as part of my query.

Currently the above errors with

Unknown fragment \"BookGridFields\"

like image 755
Adam Rackis Avatar asked Oct 12 '17 05:10

Adam Rackis


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.

What are query fragments?

A fragment is basically a reusable piece of query. In GraphQL, you often need to query for the same data fields in different queries. The code to define these fields has to be written multiple times, leading to more errors.

What is an inline fragment 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).


1 Answers

Per the graphql docs, I see that fragments are a part of the query api and not valid syntax for setting up a schema. This leads me to conclude that it is not currently possible to specify a fragment in a schema.

https://graphql.org/learn/queries/#fragments

like image 184
ericArbour Avatar answered Sep 22 '22 22:09

ericArbour