0

I have a question below:

Let's say I have a product type like this

type Option {
  id: Int!
  value: String!
}

type Product{
  id: Int!
  name: String!
  price: Float!
  options: Option
}

If I have a schema like that, every time I need product options (I have productID from the request), I need to query the entire product (with id, name, price) and I will have 2 Mysql queries to Database (1 to get product and 1 to get product options).

Should I have an additional standalone field in Query object like this to get product option base on productID? And if I need to keep nested schema like above, is there any way to get product options without executing it's parent(Product) resolver?

product_options(productId: Int!) : Option

Thanks

NHT
  • 21
  • 4

1 Answers1

0

This is more of a data relationship question I think, but nonetheless...

IMO the table for the Product Options in the SQL database (if it doesn't already) should have a column that is a foreign key to the Product that it belongs to / is associated with. Doing that allows you to easily have nested GraphQL types and field level resolvers.

Once that's done you won't need a separate query for the options structure, your field level resolver for Product.options would suffice by just querying:

{
  product(id: 123) {
    options {
      value
    }
  }
}

You can use the already fetched Product.id field in your code to run the field level query for their options row.

m_callens
  • 6,100
  • 8
  • 32
  • 54
  • Thanks for your answer. But if you do that, the product type's resolver will be executed and create a query to "product" table and when 1 more query to "options" table right? That is what I want to avoid when I only want options, not product name, price what so ever – NHT Apr 01 '20 at 16:14
  • @NHT Yes theoretically it would, and if that's what you're entirely trying to avoid then maybe this isn't the correct approach. Something to keep in mind is, while there are design patterns that are really well adopted (like the `Connection` pattern), you should ultimately design your API/schema to the needs of the consumers – m_callens Apr 01 '20 at 16:20
  • Thanks for your suggestion. – NHT Apr 01 '20 at 16:27
  • Hi @m_callens Is there any way we can get product options without executing it's parent (Product) resolver if I keep nested schema like that? – NHT Apr 02 '20 at 14:46
  • @NHT the only way that i can think of is if you wrap the other `Product` properties in a `data` object or something so `type Product` has only two fields: `data` and `options` each with their other field level resolvers. That way if you query `product.data`, only the core product fields are queried for, and if you do `product.options` only the options query will execute – m_callens Apr 02 '20 at 17:02