如何使用Graphql从Strapi中在盖茨比中查询多张图片

时间:2020-07-05 19:44:15

标签: graphql gatsby strapi

我在Strapi上的项目内容类型上设置了一个名为“图片”的多媒体(图像)字段,并添加了2个项目,每个图片包含4张图像。 我想使用Graphql在盖茨比中查询这些图像。

这是我在gatsby-config.js中的插件数组

    plugins: [
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
    `gatsby-plugin-sharp`,
    `gatsby-transformer-sharp`,
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `gatsby-starter-default`,
        short_name: `starter`,
        start_url: `/`,
        background_color: `#663399`,
        theme_color: `#663399`,
        display: `minimal-ui`,
        icon: `src/images/gatsby-icon.png`,
      },
    },
    {
      resolve: `gatsby-source-strapi`,
      options: {
        apiURL: `http://localhost:1337`,
        queryLimit: 1000,
        contentTypes: [`project`],
      },
    }]

这是我在localhost:8000 / ___ graphql上的graphql查询

query MyQuery {
  allStrapiProject {
    nodes {
      pictures {
        formats {
          thumbnail {
            childImageSharp {
              fluid {
                src
              }
            }
          }
        }
      }
    }
  }
}

这是我得到的结果

   {
  "data": {
    "allStrapiProject": {
      "nodes": [
        {
          "pictures": [
            {
              "formats": {
                "thumbnail": null
              }
            },
            {
              "formats": {
                "thumbnail": {
                  "childImageSharp": {
                    "fluid": {
                      "src": "/static/eb8a7ee6108ecc0e6185aced82c3316b/b4216/167f320a448c2d6ff65acf179ee627e2.jpg"
                    }
                  }
                }
              }
            },
            {
              "formats": {
                "thumbnail": null
              }
            },
            {
              "formats": {
                "thumbnail": null
              }
            }
          ]
        },
        {
          "pictures": [
            {
              "formats": {
                "thumbnail": null
              }
            },
            {
              "formats": {
                "thumbnail": null
              }
            },
            {
              "formats": {
                "thumbnail": null
              }
            },
            {
              "formats": {
                "thumbnail": null
              }
            }
          ]
        }
      ]
    }
  }
}

除一个缩略图外,所有缩略图均包含null。

我尝试运行“ gatsby clean”,有时即使在Strapi上没有重复图像,有时也会使查询输出在多个位置具有相同的图像url。

3 个答案:

答案 0 :(得分:1)

您需要创建一个localFile ___ NODE。

首先,您需要编辑gatsby-node.js文件。

const { createRemoteFileNode } = require(`gatsby-source-filesystem`)
exports.onCreateNode = async ({
 node,
 actions,
 store,
 cache,
 createNodeId,
}) => {
const { createNode } = actions

// replace ".sliderHome" for the name of multiple media in Strapi CMS
let sliderImages = node.sliderHome

// replace “StrapiHome” for your node type

if (node.internal.type === "StrapiHome") {
  if (sliderImages.length > 0) {
    // sliderImages.forEach(el => console.log(el))
    const images = await Promise.all(
      sliderImages.map(el =>
        createRemoteFileNode({
          url: `http://localhost:1337${el.url}`,
          parentNodeId: node.id,
          store,
          cache,
          createNode,
          createNodeId,
        })
       )
     )

    sliderImages.forEach((image, i) => {
      image.localFile___NODE = images[i].id
    })
   }
 }
}

稍后重新启动Gatsby,现在这是您的查询

query MyQuery {
  allStrapiProject {
    nodes {
      pictures {
        localFile{
          childImageSharp{
            fluid(maxWidth: 1200){
              // or for gatsby use ...GatsbyImageSharpFluid_withWebp
              src 
            }
          }
        }
      }
    }
  }
}

这对我来说可以带来高质量的多张图像,希望对您有用

答案 1 :(得分:1)

截至目前,还没有“官方”方式来实现它。但是有一种变通方法可以在构建过程中创建一个自定义节点。对于如下所示的graphql查询

query MyQuery {
  allStrapiPortfolio {
    edges {
      node {
        category {
          images {
            localFile {
              childImageSharp {
                fluid {
                  base64
                  tracedSVG
                  srcWebp
                  srcSetWebp
                  originalImg
                  originalName
                }
              }
            }
          }
        }
      }
    }
  }
}

下面给出的代码在localFile之后创建images节点。该代码应放在gatsby-node.js中。

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,
          store,
          cache,
          createNode,
          createNodeId: (id) => image.id.toString(),
        });

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

请注意,您将必须根据需要自定义代码。在我的解决方案中,由于我的数据结构,我使用了两个for循环。如果不确定或只想检查自定义代码是否有效,则可以在第一个if语句之前添加console.log(node),在第二个for循环之后添加console.log(image)(在我的情况下)。那应该给您有关数据结构以及应该以哪种方式进行操作的指示。

答案 2 :(得分:0)

尝试以下操作,替换您需要显示的值: 这里是用户头像的示例

query MyQuery {
  allStrapiUser {
      edges {
        node {
          id
          avatar {
            publicURL
            childImageSharp {
              fluid {
              src
              aspectRatio
              }
            }
          }
        }
      }
    }
}

和: const poster = data.allStrapiUser.edges[0].node

<Img fluid={{aspectRatio: 1.6, src: poster.avatar.publicURL}}/>