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.

댓글

이 블로그의 인기 게시물

[Django 공식문서 번역] REST Framework - Viewset and Router

[Django REST Framework] create() vs perform_create()

Intel Open WebRTC Toolkit(OWT) Media server 설치하는법