Fragments

GraphQL Fragments

This page explains how to use GraphQL fragments and inline fragments with the Erplain schema.

Fragments are useful to avoid repeating field selections. However, instead of relying only on GraphQL interface, you'll frequently encounter unions and inline fragments (... on Type) in the schema and examples.

Quick notes

  • A fragment defined on a concrete type can only be reused when the result is of that exact type.
  • For unions (e.g. union Employer = Customer | Supplier) you should use inline fragments ... on Customer / ... on Supplier, or include a fragment that targets Customer or Supplier inside an inline fragment.
  • It's recommended to request __typename when working with unions so you can determine which concrete type was returned.

Example 1 — Employee → employer (union Customer | Supplier)

In the Erplain schema, Employee.employer can be a Customer or a Supplier (declared via union Employer = Customer | Supplier). Example query:

query GetEmployee($id: ID!) {
  Employee(id: $id) {
    id
    first_name
    last_name
    employer {
      __typename
      ... on Customer {
        id
        label
        email
      }
      ... on Supplier {
        id
        label
        email
      }
    }
  }
}

Variables (example):

{
  "id": "1"
}

Reusing a fragment defined for a concrete type

You can define a fragment for Customer and reuse it inside an inline fragment:

fragment CustomerContact on Customer {
  id
  label
  email
}
query GetEmployeeWithFragment($id: ID!) {
  Employee(id: $id) {
    id
    employer {
      __typename
      ... on Customer {
        ...CustomerContact
      }
      ... on Supplier {
        id
        label
      }
    }
  }
}

Note: a fragment like CustomerContact cannot be applied directly to a union — it must live inside an ... on Customer { ... } clause.

Example 2 — morphTo relations (employable)

For union fields (for example employer), the approach is the same: query __typename and apply fragments or inline fragments for each possible type.

query ListEmployees {
  Employees(first: 10) {
    data {
      id
      first_name
      employer {
        __typename
        ... on Customer {
          id
          label
        }
        ... on Supplier {
          id
          label
        }
      }
    }
  }
}

Best practices

  • Always include __typename when you need to distinguish union branches.
  • Prefer small, reusable fragments (e.g. ContactFields) and include them inside inline fragments.