我一直在尝试从远程URL获取图像到Gatsby源文件系统,以利用 gatsby-image
插件的延迟加载 . 我有一个restful API,它返回带有包含图像url的字符串的json . 我跟着this guide,因为我确定如何解决这个问题 . 一切都运行良好,直到使用 createNodeField
为图像添加其他属性 . 似乎添加了属性(当我将fileNode记录到控制台时,我可以看到具有 fields
属性的对象 . 但是,当尝试查询图像时,我收到错误:
我的代码中有什么问题,或者是因为盖茨比的变化?我正在使用gatsby版本 2.0.2
. 是否有更好的选择以某种方式向图像添加其他属性,以便能够只查询所需的属性?
这是我的 gatsby.node.js
的样子:
const axios = require('axios');
const { createRemoteFileNode } = require(`gatsby-source-filesystem`);
exports.sourceNodes = ({ actions, createNodeId, node, store, cache } => {
const { createNode, createNodeField } = actions;
const processProject = project => {
project.photos.forEach(async photo => {
let fileNode;
try {
fileNode = await createRemoteFileNode({
url: photo.photo.url,
store,
cache,
createNode,
createNodeId: id => `projectPhoto-${photo.id}`,
});
await createNodeField({
node: fileNode,
name: 'ProjectPhoto',
value: 'true',
});
await createNodeField({
node: fileNode,
name: 'created_at',
value: photo.created_at,
});
} catch (error) {
console.warn('error creating node', error);
}
});
}
return axios.get(baseApiUrl).then(res => {
res.data.forEach(project => {
const nodeData = processProject(project);
createNode(nodeData);
});
});
}
1 回答
最后似乎使用带有async / await的
.forEach
由于某种原因弄乱了东西 . 为循环做一切,修复了问题,虽然eslint抱怨了很多 . 这是代码: