[GraphQL] Reuse GraphQL Selection Sets with Fragments

Fragments are selection sets that can be used across multiple queries. They allow you to refactor redundant selection sets, and they are essential when querying unions or interface types. In this lesson, we will improve our query logic by creating a fragment for the activity selection set.

To follow along with these queries, go to the Pet Library GraphQL Playground.

 

query Pet {
  petById(id:"S-2") {
    name,
      weight,
    photo {
      thumb
    },
    status,
    inCareOf {
       name
    }
  }
  allPets(category:RABBIT){
    name,
    weight,
    photo {
      thumb
    },
    status,
    inCareOf {
       name,
       username
    }
  }
}

 

We can reuse part of query with fragement:

query Pet {
  petById(id:"S-2") {
   ...PetDetail,
    inCareOf {
       ...CustomerDetail
    }
  }
  allPets(category:RABBIT){
    ...PetDetail,
    inCareOf {
       ...CustomerDetail
    }
  }
}

fragment CustomerDetail on Customer {
    name,
    username
}

fragment PetDetail on Pet {
  name,
    weight,
    photo {
      thumb
    },
    status,
}

 

posted @ 2019-08-20 17:42  Zhentiw  阅读(158)  评论(0编辑  收藏  举报