3. GRAPHQL FRAGMENTS
# Why do we need Fragments?
Fragments are used to reduce redundancy. You can think of it as something like struct in C.
For exmaple,
```
query {
Lift(id: "jazz-cat") {
name
status
capacity
night
elevationGain
trailAccess {
name
difficulty
}
}
Trail(id: "river-run"){
name
difficulty
accessedByLifts {
name
status
capacity
night
elevationGain
}
}
}
```
you can see that Lift wants
name
status
capacity
night
elevationGain
and Trail also wants those fields in "accessedByLifts"
In this case, you can use fragment
```
fragment liftInfo on Lift{
name
status
capacity
night
elevationGain
}
```
fragment can be used with preceding 3 dots.
Following query returns exactly the same result as the upper code:
```
query {
Lift(id: "jazz-cat") {
...liftInfo
trailAccess {
name
difficulty
}
}
Trail(id: "river-run"){
name
difficulty
accessedByLifts {
...liftInfo
}
}
}
fragment liftInfo on Lift{
name
status
capacity
night
elevationGain
}
```
# Advantages
You can modify the selection sets used in many different queries simply by modifying one fragment.
Fragments are used to reduce redundancy. You can think of it as something like struct in C.
For exmaple,
```
query {
Lift(id: "jazz-cat") {
name
status
capacity
night
elevationGain
trailAccess {
name
difficulty
}
}
Trail(id: "river-run"){
name
difficulty
accessedByLifts {
name
status
capacity
night
elevationGain
}
}
}
```
you can see that Lift wants
name
status
capacity
night
elevationGain
and Trail also wants those fields in "accessedByLifts"
In this case, you can use fragment
```
fragment liftInfo on Lift{
name
status
capacity
night
elevationGain
}
```
fragment can be used with preceding 3 dots.
Following query returns exactly the same result as the upper code:
```
query {
Lift(id: "jazz-cat") {
...liftInfo
trailAccess {
name
difficulty
}
}
Trail(id: "river-run"){
name
difficulty
accessedByLifts {
...liftInfo
}
}
}
fragment liftInfo on Lift{
name
status
capacity
night
elevationGain
}
```
# Advantages
You can modify the selection sets used in many different queries simply by modifying one fragment.
댓글
댓글 쓰기