0

Our apps get their data exclusively from internal graphql endpoints running on Spring Boot servers. These servers integrate with public or private APIs via CXF and/or clients generated by Swagger documents. This allows us to have a standard interface format across all of our apps, while maintaining the flexibility to use whatever a given customer's technology uses or needs.

The short question is - Is there a way in Java to Cast or Copy an instance of one class to one of its subclasses? i.e. turn a Car into a SportsCar, rather than the other way around?

OR, is there a way in graphql-java to call a method of some kind on a schema field, and define that IN the schema?

Details:

Frequently, we are given Swaggers, XSDs, or other codegen-enabling interface contracts that provide data in a format that we have to tweak. For example, we'll ingest a (silly) Swagger that generates this class:

class Customer {
  String name;
  long numberOfMinutesSinceBirth;
  ...
}

My downstream application wants a GQL schema that looks like this:

type Customer {
    name: String
    dob: LocalDate
}

So I end up having to do something like this:

class CustomerExtension {
  Customer customer;

  public CustomerExtension(Customer customer) {
     this.customer = customer;
  }
  
  ...

  public LocalDate getDob() {
     //Write code to convert numberOfMinutesSinceBirth to a LocalDate
  }
  ...
}

And I use CustomerExtension in my schema, instead. This is fine, but when I have to do this for layers of nested objects and type, I am writing a lot of translation code that is just adding bloat.

What I WANT is to be able to do something like this:

public class BetterCustomer extends Customer {

  public LocalDate getDob() {
     //Write code to convert numberOfMinutesSinceBirth to a LocalDate
  }
}

BetterCustomer betterCustomer = magicCastOrCopyFromTo(customer);

And then just have BetterCustomer in my schema.

OR

type Customer {
    name: String
    Util.getDob(numberOfMinutesSinceBirth): LocalDate
}

Which saves me the creation of a new class, beyond having to put this helper method somewhere.

IVR Avenger
  • 15,090
  • 13
  • 46
  • 57
  • You can use a custom datafetcher for dob field in the schema. Reference: https://www.graphql-java.com/documentation/data-fetching – Mat G Oct 25 '22 at 11:13

0 Answers0