Next.js基于Apollo GraphQL在getStaticProps中实现多查询获取的方法
Next.js + Apollo 在 getStaticProps 中并发拉取多个拆分查询的实现
方案一:并行执行多个独立查询(适配现有模块化结构,零侵入)
完全保留当前src/queries目录下的模块化拆分逻辑,不需要改动查询模块代码,利用Promise.all实现多请求并行发送:
- 按需导入从
index.js统一导出的所有查询import { getPost, getProduct, getMenu } from '../src/queries'; - 改写
getStaticProps逻辑,并行触发所有查询,待全部请求完成后合并数据返回export const getStaticProps = async () => { // 并行发起所有需要的查询 const [postResult, productResult, menuResult] = await Promise.all([ client.query({ query: getPost }), client.query({ query: getProduct }), client.query({ query: getMenu }), ]); // 提取各查询返回的业务数据 const postList = postResult.data.post.edges; const productList = productResult.data.product.edges; const menuConfig = menuResult.data.menu; return { props: { data: { post: postList, product: productList, menu: menuConfig, } }, revalidate: 60, }; };
- 实现优势:多请求并行执行的总耗时和单个请求接近,不会串行拉长页面构建/增量生成的时间;完全兼容现有代码结构,维护时依然可以单独调整每个查询的语句。
- 容错优化:如果不希望单个查询失败导致整页静态构建中断,可以将
Promise.all替换为Promise.allSettled,对每个请求的返回状态做判断,跳过失败的请求、正常返回其余可用数据。
方案二:合并为单条GraphQL请求(减少网络往返次数)
如果希望多个查询只通过一次HTTP请求发送给GraphQL服务端,可以将拆分的多个独立查询合并为单个请求语句:
import { gql } from '@apollo/client'; import { getPost, getProduct, getMenu } from '../src/queries'; // 合并多个独立查询的字段(需保证原查询的根字段无重名冲突) const CombinedPageQuery = gql` query PageAllData { ${getPost} ${getProduct} ${getMenu} } `; export const getStaticProps = async () => { const { data } = await client.query({ query: CombinedPageQuery }); return { props: { data: { post: data.post.edges, product: data.product.edges, menu: data.menu, } }, revalidate: 60, }; };
- 注意事项:合并查询时如果两个原查询存在重名的根字段,会触发GraphQL字段重复定义的报错;如果你的GraphQL服务端对单次请求的复杂度、查询深度有严格限制,优先选择第一种并行独立查询的方案。
内容的提问来源于stack exchange,提问作者Saghar Francis
相关产品推荐
相关产品推荐

