使用graphql和gatsby从trapi查询多个图像

问题描述

我正在尝试将一些图像映射到图像库中。每个 ID 应该有多个图像,但在 graphIQL 中只返回 1 个。

我找到了 this related thread,但我不知道应该在我的 gatsby 节点文件中放入什么。任何帮助将不胜感激

graphIQL -

graphIQL

解决方法

正如我在另一个答案中所建议的,如果循环打印相同的图像,则在内部没有从 Strapi 正确设置 id。您可以自定义 GraphQL 节点架构以添加自定义参数,以便使用 Gatsby 提供的不同 API 绕过此限制,createRemoteFileNode 应该符合您的要求。

const { createRemoteFileNode } = require(`gatsby-source-filesystem`);

exports.onCreateNode = async ({ node,actions,store,cache }) => {
  const { createNode,createNodeField } = actions;

  if (node.internal.type !== null && node.internal.type === "StrapiPortfolio") {
    for (const category of node.category) {
      for (const image of category.images) {
        console.log(image);
        const fileNode = await createRemoteFileNode({
          url: "http://localhost:1337" + image.url,cache,createNode,createNodeId: (id) => image.id.toString(),});

        if (fileNode) {
          image.localFile___NODE = fileNode.id;
        }
      }
    }
  }
};

根据您的数据结构,您可能需要更改循环,在这种情况下,图像位于 category 节点内,因此必须通过嵌套两个不同的循环来推断。

这个想法是遍历所有图像节点并添加 localFile___NODE 字段:

  image.localFile___NODE = fileNode.id;

id 之前在以下位置创建:

  createNodeId: (id) => image.id.toString(),