我一直在尝试从远程URL向Gatsby Source File系统获取图像,以利用通过gatsby-image
插件进行的延迟加载。我有一个宁静的API,它返回包含图像URL的字符串的json。我关注this guide是因为我对Gatsby Node Api很陌生,所以不确定如何解决这个问题。一切正常,直到使用createNodeField
向图像添加其他属性为止。这些属性似乎已添加(当我将fileNode登录到控制台时,我可以看到具有fields
属性的对象。但是,当尝试查询图像时,出现错误:
我想知道我的代码中是否有错误,或者是由于gatsby的更改引起的?我正在使用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);
});
});
}
答案 0 :(得分:2)
最后,由于某种原因,似乎将.forEach
与async / await一起使用会弄乱东西。尽管eslint抱怨很多,但在for循环中进行所有操作可以解决问题。这是代码:
const axios = require('axios');
const { createRemoteFileNode } = require(`gatsby-source-filesystem`);
exports.sourceNodes = ({ actions, createNodeId, node, store, cache } => {
const { createNode, createNodeField } = actions;
const processProject = project => {
for (const photo of project.photos) {
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);
});
});
}