How can I produce a graphql schema for federation with java?

2.9k Views Asked by At

My group is planning to use Apollo Gateway for federation. Therefore, we need to produce our schemas a little bit differently.

Can we produce something like this with using your amazing lib?

extend type User @key(fields: "id") {
  id: ID! @external
  reviews: [Review]
}
1

There are 1 best solutions below

1
On BEST ANSWER

You want to add some fields and directives to a type?

You can use @GraphQLContext to attach external methods as fields. Or even provide a custom ResolverBuilder that returns additional Resolvers (these later get mapped to fields). To add directives, you can create annotations meta-annotated with @GraphQLDirective (see the tests for examples). Lastly, you can of course provide a custom TypeMapper for User and fully take control of how that type gets mapped.

E.g. you can make an annotation like:

@GraphQLDirective(locations = OBJECT)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Key {
    public String[] fields;
}

If you then place this annotation on a type:

@Key(fields = "id")
public class User {
    @External //another custom annotation
    public @GraphQLId @GraphQLNonNull String getId() {...}
}

it will get mapped as:

type User @key(fields: "id") {
    id: ID! @external
}

I presume you know about @GraphQLContext, but in short:

//Some service class registered with GraphQLSchemaBuilder
@GraphQLApi
public class UserService {

    @GraphQLQuery
    public List<Review> getReviews(@GraphQLContext User user) {
        return ...; //somehow get the review for this user
    }
}

Because of @GraphQLContext, the type User now has a review: [Review] field (even though the User class does not have that field).