angeloashmore / gatsby-plugin-local-search

Gatsby plugin for providing client-side search for data available in Gatsby's GraphQL layer using a variety of engines
MIT License
51 stars 29 forks source link

querying Sharp images #32

Closed Mites-G closed 3 years ago

Mites-G commented 3 years ago

Hello!

I'm wondering if it's possible or even advised to query sharp images on this plugin's config so I can display them as thumbnails on my results.

Using ...GatsbyImageSharpFluid fragment breaks build, and deconstructing this fragment on my query results in a image with weird colors.

angeloashmore commented 3 years ago

Hi @Mites88, good question!

It is possible to include Sharp-processed images. I would advise against including the Sharp images as part of your indexed fields as your index will become gigantic. Including it as a store field is okay, as long as your store isn't too large.

I typically do not include gatsby-image data in search indexes or stores since the resulting objects are quite large. Instead, I opt for just a regular image URL. If your data comes from a source with an integration with services like Imgix or Cloudinary, you can make sure the image URL is a certain size in the index, or even generate gatsby-image objects client-side when showing results.


As far as how to use Sharp, or any other fragment, in your query, because the query is run outside of Gatsby's page queries, you need to include the whole fragment within your query option value.

For example, if you want to use ...GatsbyImageSharpFluid in your query, you can do something like this:

// gatsby-config.js

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-plugin-local-search',
      options: {
        // Alongside your other plugin options
        store: ['path', 'title', 'featuredImage'],
        index: ['title', 'rawMarkdownBody'],
        query: `
          query {
            allMarkdownRemark {
              nodes {
                id
                frontmatter {
                  path
                  title
                  featuredImage {
                    ...GatsbyImageSharpFluid
                  }
                }
                rawMarkdownBody
              }
            }
          }

          fragment GatsbyImageSharpFluid on ImageSharpFluid {
            base64
            aspectRatio
            src
            srcSet
            sizes
          }
        `
      }
    }
  ]
}

You can find all the gatsby-transformer-sharp fragments here: https://github.com/gatsbyjs/gatsby/blob/4638cd678b28f7a515df465be21d9d8bcdd71d9a/packages/gatsby-transformer-sharp/src/fragments.js

Hope that helps!

Mites-G commented 3 years ago

Thank you for your very quick response, @angeloashmore !

I confirm it does indeed work as you explained.