【发布时间】:2020-12-18 06:00:07
【问题描述】:
我正在尝试将 File 节点添加到不会自动创建它们的 gatsby 源(在本例中为gatsby-source-tumblr)。每个节点都有一个关联的图像数组,我想下载这些图像,然后使用 Gatsby-Image 进行转换。
到目前为止,这是我的代码:
exports.onCreateNode = async ({
node,
actions: { createNode, createNodeField },
store,
cache,
getCache,
createNodeId,
}) => {
if (node.internal.type === `TumblrPost`) {
const pathValue = "/posts/" + node.slug
createNodeField({
node,
name: `path`,
value: pathValue,
})
}
if (
node.internal.type === `TumblrPost` &&
node.photos &&
node.photos.length
) {
await node.photos.map(async photo => {
let fileNode
try {
fileNode = await createRemoteFileNode({
url: photo.original_size.url,
parentNodeId: node.id,
getCache,
createNode,
cache,
createNodeId,
store,
})
// Adds a field `localFile` to the node
// ___NODE appendix tells Gatsby that this field will link to another node
if (fileNode) {
photo.localFile___NODE = fileNode.id
}
} catch (err) {
console.warn(err)
}
})
}
}
正如我在多个教程中所建议的那样,我使用createRemoteFileNode 来下载图像并将它们添加为文件节点。 这部分有效,我可以看到正在下载的图像,并且在 GraphiQL 中的 allImageSharp 类别下可以看到许多项目。
但是我似乎无法让与父节点的关联起作用。做类似photo.localFile___NODE = fileNode.id 的事情似乎没有任何效果。尝试将一张图像添加到父节点(帖子)似乎不起作用:在 GraphiQL 检查器中查看帖子节点时,没有文件节点的痕迹。
我感觉我可能遗漏了一些明显的东西,但我已经摆弄了几个小时,似乎无法弄清楚。
任何帮助将不胜感激!
【问题讨论】:
-
会不会是
fileNode还没有id?在这个例子中alexluong.com/blog/gatsby-image-sharp-from-url 他们使用createNodeId这样createNodeId: id => `dog-image-sharp-${id}`在使用createRemoteFileNode时使用createRemoteFileNode