简体   繁体   English

如何避免graphql请求中的代码重复?

[英]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.我正在用 Gatsby 和 GraphQl 制作博客,但我找不到避免查询中代码重复的方法。 I have 3 almost identical queries:我有 3 个几乎相同的查询:

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.我的问题是,我拥有的不仅仅是 2 个参数“id”和“nom”,因此每次我在无头 CMS 中编辑字段时,很难在不同页面中维护这 3 个请求。

I tried to do something like this but I got this error : "String interpolation is not allowed in graphql tag:"我试图做这样的事情,但我得到了这个错误:“graphql 标签中不允许字符串插值:”

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 ?有没有一种方法可以将我的请求的通用元素(“边缘”内的所有内容)放在一个地方并在不同的请求中使用它?

I think you're looking for fragments :我认为您正在寻找片段

GraphQL includes reusable units called fragments. GraphQL 包括称为片段的可重用单元。 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:以下是如何使用片段解决上述情况的示例:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM