1

this is my first post on stackoverflow (Long time reader). I mainly come from a Python background and am fairly new to Ruby. I'm wondering on what's the recommended way to structure a Ruby GraphQL API like the following. Each one of the keys has a resolver that requests a different websites API to fetch the related data. These are currently nested under cars in the following way (I removed the actual http sources they are hitting since you need api keys):

Types::CarsType = GraphQL::ObjectType.define do
  name "Cars"

  field :count, types.ID
  field :contact, types.String

  field :prices do
    type Types::PricesType
    resolve ->(obj, args, ctx) {
       HTTParty.get('http://example.com').parsed_response.fetch('some_key').map { |data| OpenStruct.new(data) }
    }
  end

  field :inquiries do
    type Types::InquiriesType
    resolve ->(obj, args, ctx) {
       HTTParty.get('http://example1.com').parsed_response.fetch('some_key').map { |data| OpenStruct.new(data) }
    }
  end
end

Types::InquiriesType = GraphQL::ObjectType.define do
  name "Inquiries"
  field :name, types.String
  field :phone, types.String
end
Types::PricesType = GraphQL::ObjectType.define do
  name "Prices"
  field :max, types.String
  field :min, types.String
  field :suggested, types.String
end
Types::QueryType = GraphQL::ObjectType.define do
  name 'Query'

  field :cars, types.String do
    type Types::CarsType

    argument :brand, !types[types.String]

    resolve ->(obj, args, ctx) {
       HTTParty.get('http://example2.com').parsed_response.fetch('some_key').map { |data| OpenStruct.new(data) }
    }
  end
end

An example query:

query {
  cars(brand: "ford") {
    count
    contact

    prices {
      max
      min
      suggested
    }

    inquiries {
      name
      phone
    }
  }
}

This works fine but I feel like the approach isn't using GraphQL to the fullest. Some immediate problems when I look at it is that If you were to make a query like so, it would now make two API requests when only one is needed (the customer is not requesting any fields on cars, just inquiries). Inquiries is an attribute of cars, so I think it makes sense to be nested under cars?

query {
  cars(brand: "ford") {
    inquiries {
      name
      phone
    }
  }
}

I've looked into connections, but I'm not sure if this is the correct use case for them. Is someone with experience in designing solid GraphQL APIs able to weigh in? Should I be trying to leverage unions or interfaces somehow? Thank you so much.

4

0 回答 0