Home > Software design >  How to avoid code duplication in graphql request?
How to avoid code duplication in graphql request?

Time:11-17

I am making a blog with Gatsby and GraphQl but I can't find a way to avoid code duplication in my queries. I have 3 almost identical queries:

graphql(`
        {
          allContentfulRecette {
            edges {
              node {
                id
                nom
              }
            }
          }
        }
    `)
graphql`
        query IndexQuery {
          posts : allContentfulRecette(sort: {fields: dateDePublication}){
            edges {
              node {
                id
                nom
              }
            }
          }
        }
    `
graphql`
        query allRecettesByCategorie($slug: String!) {
          recettes : allContentfulRecette(
           sort: {fields: dateDePublication}
           filter: {categorie: {elemMatch: {slug: {eq: $slug}}}}
          ) {
            edges {
              node {
                id
                nom
              }
            }
          }
        }
    `

As you can see they are very similar, the second one just has a sort, and the third one has a sort and a filter. My problem is that I have way more than just the 2 parameters 'id' and 'nom', so having those 3 requests in different pages is hard to maintain each time I edit a field in my headless CMS.

I tried to do something like this but I got this error : "String interpolation is not allowed in graphql tag:"

export const pageQuery = graphql`
  query IndexQuery {
    posts : allContentfulRecette(sort: {fields: dateDePublication}){
    ${allContentfulRecette}
    }
  }
`

Is there a way I can have the common elements of my request (everything inside "edges") in one place and use it in different request ?

CodePudding user response:

I think you're looking for fragments:

GraphQL includes reusable units called fragments. Fragments let you construct sets of fields, and then include them in queries where you need to. Here's an example of how you could solve the above situation using fragments:

  • Related