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 targetsCustomerorSupplierinside an inline fragment. - It's recommended to request
__typenamewhen 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
firstName
lastName
employer {
__typename
... on Customer {
id
name
email
}
... on Supplier {
id
name
vatNumber
}
}
}
}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
name
email
}
query GetEmployeeWithFragment($id: ID!) {
employee(id: $id) {
id
employer {
__typename
... on Customer {
...CustomerContact
}
... on Supplier {
id
name
}
}
}
}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)
employable)For fields using morphTo (for example employable), the approach is the same: query __typename and apply fragments or inline fragments for each possible type.
query ListEmployees {
employees(first: 10) {
data {
id
firstName
employable {
__typename
... on Customer {
id
name
}
... on Supplier {
id
name
}
}
}
}
}Best practices
- Always include
__typenamewhen you need to distinguish union branches. - Prefer small, reusable fragments (e.g.
ContactFields) and include them inside inline fragments.
