首页 > 解决方案 > Gatsby 组件中的多个 graphql 查询

问题描述

我需要在一个组件和gatsby-node.js文件中运行多个 graphQL 查询。(因为 Prismic 每个答案限制为 20 个条目......)

我尝试了以下方法,只是想看看我是否可以在默认函数中创建 graphql 循环:

export default () => {
  async function allPosts() {
    let data

    await graphql(`
      query allDitherImages {
        prismic {
          allProjects(sortBy: meta_firstPublicationDate_DESC) {
            totalCount
            pageInfo {
              startCursor
              endCursor
              hasNextPage
              hasPreviousPage
            }
            edges {
              node {
                cover_image
                cover_imageSharp {
                  name
                }
              }
            }
          }
        }
      }
    `).then(initialRes => {
      data = initialRes
    })

    return data
  }

  allPosts().then(result => {
    console.log(result)
  })
  return null
}

但后来盖茨比告诉我Gatsby related 'graphql' calls are supposed to only be evaluated at compile time, and then compiled away. Unfortunately, something went wrong and the query was left in the compiled code.

如何运行多个 graphql 查询?

提前谢谢你:)迈克尔

标签: graphqlgatsbyprismic.io

解决方案


gatsby -source-prismic-graphql包将为您的所有 Prismic 项目(不仅仅是前 20 个)创建页面,因为它会遍历引擎盖下的所有项目,所以如果您正在寻找,我建议您考虑使用它为所有这些项目生成页面。

但是,如果您需要获取所有项目并将它们传递到 pageContext 或其他内容中,则需要自己在 gatsby-node 中进行递归。

在 gatsby-node 中,定义查询后,您可以使用类似这样的方法来迭代结果并推送到数组。

let documents = [];
async function getAllDocumentsRecursively (query, prop, endCursor = '') {
  const results = await graphql(query, { after: endCursor })
  const hasNextPage = results.data.prismic[prop].pageInfo.hasNextPage
  endCursor = results.data.prismic[prop].pageInfo.endCursor

  results.data.prismic[prop].edges.forEach(({node}) => {
    documents.push(node)
  });

  if (hasNextPage) {
    await getAllDocumentsRecursively(query, 'allDitherImages ', endCursor)
  }
}
await getAllDocumentsRecursively(documentsQuery, 'allDitherImages ');

然后在您的 createPage 中,将数组传递到上下文中:

createPage({
    path: `/`+ node._meta.uid,
    component: allDitherTempate,
    context: {
      documents: documents
    }
  })

推荐阅读