首页 > 解决方案 > 将一个graphql查询的结果输入另一个?

问题描述

为什么我需要这样做:我正在使用 graphql + gatsby + contentful。我在 Contentful 中使用富文本字段,它允许在 markdown 中嵌入对象引用。我想显示嵌入的条目。

我的查询如下所示:

export const pageQuery = graphql`
  query BlogPostBySlug($slug: String!) {
      richTextField {
        content {
            nodeType
            data {
                target {
                    sys {
                        id
                    }
                }
            }
        }
      }
    }
  }
`

richTextField.content回来看起来像这样:

{
  "data": {
    "target": {
      "sys": {
        "id": "5wVh2a6XvySacEioOEMyqQ",
      }
    }
  },
}

id,“5wVh2a6XvySacEioOEMyqQ”,是对另一个数据库条目的引用。我可以看到这可能如何工作的两种潜在方式:

  1. 告诉 graphql 查询中的 id 引用另一个数据库模型并让它自动填充字段的某种方式。这可能吗?

  2. 获取此查询的结果,收集所有 id 并构造另一个查询,在其中搜索具有这些 id 的条目。看起来 apollo 可能是一个解决方案,但它不适用于 gatsby。这可能吗?

做这个的最好方式是什么?

谢谢!:)

标签: graphqlgatsbycontentful

解决方案


您可以尝试使用外键来关联节点。

在您的gatsby-node.js文件中,您需要添加一个带有要链接的节点___NODEid 的密钥:sys

exports.sourceNodes = async ({ getNodes, actions, createContentDigest }) => {
  // find all the sys nodes - you'll need to alter this filter to get the right one
  const sysNodes = getNodes().filter(node => node.internal.type === 'File');

  // go through the posts to map the sys nodes
  // these nodes may already exist, so you could filter `getNodes` like above
  const postData = howeverYouGetDataFromContentful();

  postData.forEach(post => {
    const sys = sysNodes.find(embedded => embedded.id === post.data.target.embedded.id);

    // This will create a brand-new node.
    // If your posts already exist, then use `createNodeField` mentioned below
    const node = {
      id: post.id,
      children: [],
      internal: {
        type: 'post',
        mediaType: 'text/json',
        contentDigest: createContentDigest(JSON.stringify(post))
      },
      sys___NODE: sys.id
    };

    actions.createNode(node);
  });
}

如果在调用时节点已经存在sourceNodes(它们可能会使用 Contentful),那么您可以使用getNodes. 您可能还需要使用createNodeField而不是createNode,如此处所述: https ://github.com/gatsbyjs/gatsby/issues/3129#issuecomment-360927436以避免重新创建节点。


推荐阅读