kirillplatonov / shopify_graphql

Less painful way to work with Shopify Graphql API in Ruby.
MIT License
59 stars 9 forks source link

README example for collection/edge parsing? #6

Closed forsbergplustwo closed 1 year ago

forsbergplustwo commented 2 years ago

Thanks for this gem, very nicely done! When working with xxxxxFields classes, it took me a while to work out the best way to parse collections, without complicating each querying class. Came up with the following in the end:

class ProductFields
  FRAGMENT = <<-GRAPHQL
    fragment ProductFields on Product {
      id
      title
      featuredImage {
        transformedSrc(maxHeight: 300, maxWidth: 300, scale: 2)
      }
    }
  GRAPHQL

  def self.parse(product)
    OpenStruct.new(
      id: product.id,
      title: product.title,
      image_src: product.featuredImage&.transformedSrc,
    )
  end

  def self.parse_collection(products)
    products&.edges&.map do |edge|
      OpenStruct.new(
        cursor: edge.cursor,
        node: ProductFields.parse(edge.node)
      )
    end
  end
end

Happy to update README if you think it could be useful to others, or you have another suggested way?

kirillplatonov commented 2 years ago

Yeah, adding that example to README would be nice. Very useful!

BTW do you still use GraphqlResponseRubyfier for wrapping responses?

forsbergplustwo commented 2 years ago

Nice, will create PR :) Not using GraphqlResponseRubyfier as once I realised edges need the cursor, it was just as good going with json parse using the object_class: OpenStruct like you are. And it's much more foolproof/simpler than having the custom rybyfier.

kirillplatonov commented 1 year ago

Added examples for collections to README