Resolver classes for GraphQL in Magento can be used in an incredibly flexible way, but if you’re used to building endpoints for traditional API schemes like REST, there’s a little bit of un-learning to do.
With REST, each endpoint corresponds with one entry point in the code. All logic branches out from that one entry point, and the data that must be assembled and returned is uniform; there’s no worrying about whether certain fields or data structures should be fetched, because the schema’s always the same.
GraphQL, however, offers the client the flexibility to specify exactly what they want returned, and that means the serving application must be appropriately nimble. GraphQL queries are resolved not just from one entry point, but with a recursive process where every queried field can be associated with its own resolver logic that further refines or adds to the “resolved” data from its parents.
Consider the native GraphQL query for products. One of the fields that can be selected for each item in the results set is related_products. Looking up that data requires additional DB queries beyond the initial products list, and the application shouldn’t do that work if related_products isn’t included in the client’s field selection! If we think of the Magento\CatalogGraphQl\Model\Resolver\Products class that handles the products query as a single entry point, we’d find that class doing some nightmarishly deep inspection of the incoming query to figure out whether to add related products or not. That’s brittle, and it doesn’t allow the GraphQL runtime to do its job! Instead, a separate resolver class on the related_products field is executed only if it’s needed, and combined with some asynchronous logic, it wires up related product data in an efficient and performant way. No need for writing code that inspects and analyzes the client’s query!
Director of Training and Development at SwiftOtter -@ChrisNanninga