Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

225
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda