Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

224
Views
How to avoid code duplication in graphql request?

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 ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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:

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!