graphql - 将一个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”,是对另一个数据库条目的引用。我可以看到这可能如何工作的两种潜在方式:
告诉 graphql 查询中的 id 引用另一个数据库模型并让它自动填充字段的某种方式。这可能吗?
获取此查询的结果,收集所有 id 并构造另一个查询,在其中搜索具有这些 id 的条目。看起来 apollo 可能是一个解决方案,但它不适用于 gatsby。这可能吗?
做这个的最好方式是什么?
谢谢!:)
解决方案
您可以尝试使用外键来关联节点。
在您的gatsby-node.js
文件中,您需要添加一个带有要链接的节点___NODE
id 的密钥: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以避免重新创建节点。
推荐阅读
- julia - 如何计算Julia的日出和日落
- javascript - 将 Mongoose Node.js 中的对象数组保存到 HTML Javascript 中的数组
- html - Google Analytics(分析)广告系列 URL 跟踪未显示在 Google Analytics(分析)仪表板中
- c - 那是矩阵分配是错误的?
- c - c语言中的预期标识符
- powershell - 将 API 响应中的多个值写入 csv
- sql-server - SCOM 错误 26319 最大递归 100 在语句完成之前已用完
- python - Pandas:高效插入大量行
- postgresql - pgBench 致命:需要至少 2003 个打开文件,但系统限制为 1024
- python - 在 CV2 Python 中实现发光滤镜