Node.js › GraphQL
What is the purpose of GraphQL fragments, and how do they help avoid duplicating field selections across multiple queries?
IntermediateAnswer
A fragment defines a reusable, named set of fields on a specific type, which can then be included (spread) into multiple different queries or mutations wherever that same set of fields is needed -- this avoids repeating an identical, potentially large list of fields across every query that needs the same shape of data, and makes it easier to keep field selections consistent when the same data shape (like a summary view of a User) is used in several different places throughout an application.
fragment UserSummary on User {
id
name
avatarUrl
}
query GetPost {
post(id: "1") { title, author { ...UserSummary } }
}
query GetComment {
comment(id: "1") { text, author { ...UserSummary } }
}Real-world example A frontend application defines a UserSummary fragment once and reuses it across a dozen different queries that all need to display the same basic author information, ensuring that if the summary fields ever need to change, only the single fragment definition needs updating rather than every individual query.