-
Notifications
You must be signed in to change notification settings - Fork 8
Attaching S3 images to another node #79
Description
I just wanted to mention the idea of maybe documenting another way of using this plugin. The site I am building is an e-commerce platform with thousands of images (for all the products). This presented a major issue with using gatsby which is querying images. For a long time, I had a component that queried all images and matched them up to their respective product. (Like proposed in this stack overflow) This is highly inefficient, throwing warnings about the duration of the query.
An alternate to this is the attach the imageFile to the product on the data level, rather than when trying to render.
src/gatsby-api/create-resolvers/index.js
const resolvers = {
AWSAppSync_Product: {
imageFile: {
type: 'File',
resolve: async (source, args, context, info) => {
const node = await context.nodeModel.runQuery({
query: {
filter: {
Key: { eq: source.image1 }
}
},
type: 'S3Object',
firstOnly: true
});
if (node && node.imageFile) return node.imageFile;
}
},
},
}
module.exports = {
resolvers
}
gatsby-node.js
exports.createResolvers = async ({ createResolvers }) => {
createResolvers(resolvers)
}
src/components/image/index.js
import React from 'react'
import Img from 'gatsby-image'
export const Image = props => {
if (props.imageFile && props.imageFile.childImageSharp && props.imageFile.childImageSharp.fluid) {
return <Img className={props.imgClassName} alt={props.alt} fluid={props.imageFile.childImageSharp.fluid} />;
}
};
Then use it like:
<Image
imageFile={product.imageFile}
alt=""
/>
AWSAppSync_Product
is the type of node I am attaching my File to. (which can be found in the graphql playground on localhost). The resolve will match the Key
of the S3Object
with image1
(which is a string) on the product. This allows me to directly use the product images without having to run a query inside the image component.
In my opinion, this is a valuable piece of information once you wrap your head around it and it certainly has helped me a lot. Thanks @Js-Brecht.