Distelli / graphql-apigen

Generate Java APIs with GraphQL Schemas
Apache License 2.0
66 stars 20 forks source link

Add fetcher for fields with arguments #30

Open amareensaleh opened 6 years ago

amareensaleh commented 6 years ago

Assume we have a graphql type Foo. The generator will generate classes Foo, Foo.Impl and FooTypeProvider which is great.

In our usecase, we'd for the most part use Foo.Impl to carry information back and forth. However, things get a little tricky when it comes down to Fields with arguments. In that case, we'd like to provide a custom implementation of Foo --only-- for fields with arguments which in turn will handle fetching such fields probably from somewhere else (i.e., not straight from Foo). This is kind of like a lazy out of band information fetching, if that makes sense.

As of now, if I do provide my own implementation of Foo say FooFetcher, then the latter will take effect disregarding the original Foo.Impl which had all the information except for the fields with arguments. To resolve this, I had come up with the solution below. It is a decorator which delegates everything except for the fields with arguments. I am wondering if my approach is sound? And if so, can such a fetcher maybe added to the stg template to be generated by default?

public class FooFetcher implements Foo {
    private Foo foo = null;
    @Override
    public String description(DescriptionArgs args) {
        if ("cool".equals(args.getFormat())) {
            return "A cool description";
        } else {
            return "A not so cool description";
        }
    }
    @Override
    public final Foo resolve(DataFetchingEnvironment env) {
        if (foo == null) {
            this.foo = env.getSource();
        }
        return this;
    }
    @Override
    public final Integer getFooId() {
        return foo.getFooId();
    }
    @Override
    public final String getPhoneNumber() {
        return foo.getPhoneNumber();
    }
}