Shopify API GraphQL get multiple image thumbnails in single request

Viewed 965

I'm working with the Shopify API using graphql, We've been tasked to implement srcset images to speed up page load times, however I'm having trouble generating a query which will pull multiple size urls.

query ($tag: String!) {
  products(first: 10, query: $tag) {
    edges {
      cursor
      node {
        id
        tags
        handle
        images(first:1, maxWidth:360) {
          edges {
            node {
              src
              __typename
            }
            __typename
          }
          __typename
        }
      }
      __typename
    }
    __typename
  }
}

this query works at pulling in a single image url with a max width of 360px, however if I do something similar to the below (which I would hope would generate a url for a 360px image and a 720px image, then I get the error "message": "Field 'images' has an argument conflict: {first:\"1\",maxWidth:\"360\"} or {first:\"1\",maxWidth:\"720\"}?",

query ($tag: String!) {
  products(first: 10, query: $tag) {
    edges {
      cursor
      node {
        id
        tags
        handle
        images(first:1, maxWidth:360) {
          edges {
            node {
              src
              __typename
            }
            __typename
          }
          __typename
        }
        images(first:1, maxWidth:720) {
          edges {
            node {
              src
              __typename
            }
            __typename
          }
          __typename
        }
      }
      __typename
    }
    __typename
  }
}

Any advice on how I can structure my query so it pulls in two different size thumbnails?

Thanks!

2 Answers

As @xadm mentioned you can use aliases:

        small_image: images(first:1, maxWidth:360) {
          edges {
            node {
              src
            }
          }
        }
        large_image: images(first:1, maxWidth:720) {
          edges {
            node {
              src
            }
          }
        }

You add just some names before the images call of your choice.

But your approach is deprecated, you should use transformedSrc instead.

So it will become:

        images(first:1) {
          edges {
            node {
              originalSrc
              large: transformedSrc(maxWidth: 720)
              small: transformedSrc(maxWidth: 360)
            }
          }
        }

Correct ... but note that as of Mar 2022, transformedSrc is deprecated in favor of url. Thus, the first works but is deprecated in favor of the second:

        smallA: transformedSrc(maxWidth: 64)

        smallB: url(transform: {maxWidth: 64})
Related