commercetools / commercetools-sdk-java-v2

The e-commerce SDK from commercetools for Java.
https://commercetools.github.io/commercetools-sdk-java-v2/javadoc/index.html
Apache License 2.0
34 stars 15 forks source link

Best practices for grapqhl requests #247

Closed ahmetoz closed 1 year ago

ahmetoz commented 2 years ago

Http client throws exceptions in general (e.g: not found) but an error on grapqhl is returning 200 without a data but with a GraphQLError type.

Would it not be better to pass an exception with errors list in it, so it could pass by the error handler of the http client as others ? Otherwise for every grapqhl a manual null checks will be required if you don't implement in the first place it will look like a simple NPE 🤔

In general, I could not find any documentation for usage of grapqhl and handling errors of it, what do you think best way to handle ? Also some utilities like to chunk or paginated grapqhl requests might be really helpful. Is there a plan to provide those as part of the SDK ?

I've done a POC here for the aforementioned cases.

jenschude commented 2 years ago

There are some possible ways to go here.

One is to create a specific middleware that checks if in the response body the error field is not empty and raises an exception. But as the data field could still be filled this may be not wanted.

Another one is using a thenApply and first check for the errors field and raise an exception. You could even put this inside a method to be referenced as lambda.

The third option is to directly deserialize to a class structure representing the queried data.

And last but not least use one of the many GraphQL client libraries for Java which help in either creating the response classes or writing the queries based on the models. E.g.: Netflix DGS or Apollo Java client

I added a small test showing how to deserialize to specific classes with https://github.com/commercetools/commercetools-sdk-java-v2/blob/main/commercetools/commercetools-sdk-java-api/src/integrationTest/java/commercetools/graphql/GraphQLTest.java

jenschude commented 1 year ago

With the latest release (14.3.0) you now have the possibility to create type safe queries.