gatsby & graphql : filtering for a specific single image

爷,独闯天下 提交于 2020-05-30 03:58:16

问题


I don't really understand graphql or gatsby that well but I believe all my images are loaded into graphql by putting this in my gatsby-config.js

    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: path.join(__dirname, `src/assets/images`),
      },
    },

I am then trying to query a specific image which I can do with

    query MyQuery {
      allImageSharp(filter: {id: {eq: "7acfccd5-4aef-532b-8889-9d844ae2068b"}}) {
        edges {
          node {
            sizes {
              sizes
              srcSet
              src
              aspectRatio
            }
            id
          }
        }
      }
    }

And this returns what I want, but the id that I have to enter for this query is 7acfccd5-4aef-532b-8889-9d844ae2068b. Is this id even going to stay the same if I put in my code? Is there a way to set the id to something more sensical?

If I save my query to a variable data, it turns out that on Netlify data.allImageSharp.edges[0] is null, while locally this value will return what I need

I'm looking for the best way to query a single image. Not multiple images. If I could set my own id's then I could query these.


Update

I found an example in the gatsby-source-filesystem documentation, but don't really know how to add it to my code

    createRemoteFileNode({
       // The source url of the remote file
       url: `https://example.com/a-file-without-an-extension`,
       parentNodeId: node.id,
       getCache,
       createNode,
       createNodeId,
       // if necessary!
       ext: ".jpg",
       name: "image",
     })

gatsby-node.js

    const { createFilePath } = require(`gatsby-source-filesystem`)
    const path = require("path")
    
    const replacePath = path => (path === `/` ? path : path.replace(/\/$/, ``))
    
    exports.createPages = async ({ actions: { createPage }, graphql }) => {
      const postTemplate = path.resolve(`src/components/Article/index.tsx`)
    
      const result = await graphql(`
        {
          allMarkdownRemark(
            sort: { order: DESC, fields: [frontmatter___date] }
     
          ) {
            edges {
              node {
                fields {
                  slug
                }
              }
            }
          }
        }
      `)
    
      if (result.errors) {
        return Promise.reject(result.errors)
      }
    
      result.data.allMarkdownRemark.edges.forEach(({ node }) => {
        createPage({
          path: replacePath(node.fields.slug),
          component: postTemplate,
        })
      })
    }
    
    exports.onCreateNode = ({ node, getNode, actions }) => {
      if (node.internal.type === `MarkdownRemark`)
        actions.createNodeField({
          node,
          name: `slug`,
          value: replacePath(createFilePath({ node, getNode, basePath: `pages` })),
        })
    }

gatsby-config.js

    const path = require(`path`)
    
    const author = {
      firstname: "Gatsby",
      lastname: "framework",
    }
    
    module.exports = {
      siteMetadata: {
        title: `${author.firstname}'s Blog`,
        description: `Not everyone can be Gandhi, but each of us has the power to make sure our own lives count – and it’s those millions of lives that will ultimately build a better world. – Jeffrey Skoll`,
        author: `${author.firstname} ${author.lastname}`,
        authorDescription: "tries to make the world a better place",
        socials: {
          linkedin: "https://www.linkedin.com/in/pierre-alexis-blond-00924b158/",
          twitter: "https://twitter.com/_pablond",
          github: "https://github.com/PABlond",
        },
        themeColor: "#542C85",
        siteUrl: "https://friendly-cray-96d631.netlify.com/",
        image: "https://example.com/images/My%20Logo.png",
        domain: "https://my-netlify-name.netlify.app"
      },
      plugins: [
        {
          resolve: "gatsby-plugin-web-font-loader",
          options: {
            google: {
              families: ["Mansalva", "Playfair Display", "Source Sans Pro"],
            },
          },
        },
        {
          resolve: `gatsby-source-filesystem`,
          options: {
            name: `images`,
            path: `${__dirname}/src/assets/images`,
          },
        },
        {
          resolve: `gatsby-source-filesystem`,
          options: {
            name: `images`,
            path: path.join(__dirname, `src/assets/images`),
          },
        },
        {
          resolve: `gatsby-source-filesystem`,
          options: {
            path: `${__dirname}/content/markdown/`,
            name: `markdown-pages`,
          },
        },
        {
          resolve: `gatsby-plugin-create-client-paths`,
          options: { prefixes: [
            `/contact/*`,
            `/partners/*`,
            `/publications/*`
          ] },
        },
        {
          resolve: `gatsby-plugin-manifest`,
          options: {
            name: `gatsby-starter-default`,
            short_name: `starter`,
            start_url: `/`,
            background_color: `#fff`,
            theme_color: `#542C85`,
            display: `minimal-ui`,
            icon: `src/assets/images/gatsby-icon.png`,
          },
        },
        {
          resolve: `gatsby-transformer-remark`,
          options: {
            plugins: [
              'gatsby-remark-relative-images',
              {
                resolve: `gatsby-remark-images`,
                options: {
                  linkImagesToOriginal: false,
                },
              },
            ],
          },
        },
        {
          resolve: 'gatsby-plugin-root-import',
          options: {
            "components": path.join(__dirname, "src/components"),
            // "layouts": path.join(__dirname, "src/layouts"),
            "styles": path.join(__dirname, "src/assets/styles"),
            "types": path.join(__dirname, "src/types"),
            "enums": path.join(__dirname, "src/enums"),
            "interfaces": path.join(__dirname, "src/interfaces"),
            "data": path.join(__dirname, 'src/data'),
            "pages": path.join(__dirname, 'src/pages')
          }
        },
        `gatsby-plugin-react-helmet`,
        `gatsby-transformer-sharp`,
        `gatsby-plugin-sharp`,
        `gatsby-plugin-typescript`,
        `gatsby-plugin-sass`,
        `gatsby-plugin-offline`,
        `gatsby-plugin-graphql-loader`
      ],
    }

回答1:


With this snippet:

{
  resolve: `gatsby-source-filesystem`,
  options: {
    name: `images`,
    path: path.join(__dirname, `src/assets/images`),
  },
},

Basically you are telling your GraphQL schema that will find images in src/assets/images folder so you will be able to query all the content inside this folder via GraphQL. You are specifying the source for your data.

From gatsby-source-filesystem documentation:

The plugin creates File nodes from files. The various “transformer” plugins can transform File nodes into various other types of data e.g. gatsby-transformer-json transforms JSON files into JSON data nodes and gatsby-transformer-remark transforms markdown files into MarkdownRemark nodes from which you can query an HTML representation of the markdown.

Answering your question, of course, you can filter and sort for any property or node that your image has, such as name, path, extension, etc. You may find a useful and autocompletion tool for your queries under /___graphql path when you run a gatsby develop command. This will help you to check out what parameters can be queried and filtered.



来源:https://stackoverflow.com/questions/61861830/gatsby-graphql-filtering-for-a-specific-single-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!