我需要在组件中和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查询?
预先感谢您:) 迈克尔
答案 0 :(得分:1)
gatsby-source-prismic-graphql软件包将为您的所有Prismic物品(不仅仅是前20个)创建页面,因为它会遍历引擎盖下的所有物品,因此,如果您愿意,建议您使用它希望为所有这些项目生成页面。
但是,如果您需要获取所有项目并将其传递到pageContext之类的东西中,则需要自己在gatsby节点中进行递归。
在gatsby节点中,定义查询后,可以使用类似的方法迭代结果并推送到数组。
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
}
})