如何避免 graphql 请求中的代码重复?
How to avoid code duplication in graphql request?
我正在使用 Gatsby 和 GraphQl 创建博客,但我找不到避免查询中代码重复的方法。
我有 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
}
}
}
}
`
如您所见,它们非常相似,第二个只有排序,第三个有排序和过滤器。
我的问题是我拥有的不仅仅是 2 个参数 'id' 和 'nom',所以每次我在无头 CMS 中编辑一个字段时,很难在不同的页面中维护这 3 个请求。
我试图做这样的事情,但我得到了这个错误:“graphql 标记中不允许字符串插值:”
export const pageQuery = graphql`
query IndexQuery {
posts : allContentfulRecette(sort: {fields: dateDePublication}){
${allContentfulRecette}
}
}
`
有没有一种方法可以将我请求的公共元素(“边缘”内的所有内容)放在一个地方并在不同的请求中使用它?
我想你在找 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:
我正在使用 Gatsby 和 GraphQl 创建博客,但我找不到避免查询中代码重复的方法。 我有 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
}
}
}
}
`
如您所见,它们非常相似,第二个只有排序,第三个有排序和过滤器。 我的问题是我拥有的不仅仅是 2 个参数 'id' 和 'nom',所以每次我在无头 CMS 中编辑一个字段时,很难在不同的页面中维护这 3 个请求。
我试图做这样的事情,但我得到了这个错误:“graphql 标记中不允许字符串插值:”
export const pageQuery = graphql`
query IndexQuery {
posts : allContentfulRecette(sort: {fields: dateDePublication}){
${allContentfulRecette}
}
}
`
有没有一种方法可以将我请求的公共元素(“边缘”内的所有内容)放在一个地方并在不同的请求中使用它?
我想你在找 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: