Yegor
Yegor

Reputation: 3950

How to implement GraphQL fragments in schema?

I try to use fragments in GraphQL

There is my schema

user/getUser.gql

input GetUserByUsernameInput {
  username: String!
}

fragment UserFragment on User {
  username
  information
  pictureUrl
}

type UserType {
  ...UserFragment
}

type GetUserByUsernameResponse {
  user: UserType
  errors: [Error]!
}

type Query {
  getUserByUsername(input: GetUserByUsernameInput!): GetUserByUsernameResponse!
}

shared/User.gql

type User {
  id: Int!
  username: String!
  email: String!
  information: String
  pictureUrl: String
}

And I got dummy error

(node:26206) UnhandledPromiseRejectionWarning: Syntax Error: Expected Name, found ...

GraphQL request (12:9)
11: type UserType {
12:   user: ...UserFragment
            ^
13: }

How should my code looks like to use GraphQL fragments?

PS. I use graphql-code-generator

Upvotes: 1

Views: 1259

Answers (1)

David Maze
David Maze

Reputation: 159875

Fragments only exist in queries; you can't use them in the schema language.

In your example the response should include a reference to the User that's being returned:

type GetUserByUsernameResponse {
  user: User
  errors: [Error]!
}

When you make a query, though, you can include the fragment.

query WhoAreYou($username: String!) {
  getUserByUsername(input: {username: $username}) {
    user { ...UserFragment }
    errors { message }
  }
}

fragment UserFragment on User {
  username
  information
  pictureUrl
}

Fragments tend to be somewhat more useful if either you have reason to request the same fields on the same type of object multiple times in one query, or if you have a client library that's capable of picking fragments out of a "library" of GraphQL queries you'll use multiple places. (For example, the Ruby graphql-client gem can be configured with a file of many queries, and you can make a specific query out of it by operation name and it will make a query with that operation and any fragments it references, so you can reuse the same fragments across several queries.)

Upvotes: 4

Related Questions