How do I logically split up my GraphQL schema and

2020-07-26 11:14发布

问题:

At the moment, all my query resolvers are under a single Query class and a single Query schema / type as such:

schema {
    query: Query #I'd prefer UserQueries and OrganisationQueries
    mutation: UserMutations
    mutation: OrganisationMutations
}

type Query {
    fetchUser(email: String): User
    listOrganisations(max: Int): [GenericListing]
}

...

And all my queries in one class:

@Component
public class Query implements GraphQLQueryResolver {

    public List<GenericListing> listOrganisations (Integer max) {
        ...
    }

    public User fetchUser (String email) {
        ...
    }
}

I've managed to split up and logically separate my mutations by User and Organisation!

@Component
public class UserMutations implements GraphQLMutationResolver {

    public User createUser(String firstname, String lastname, String email, String msisdn, String password) {
        ...
    }
}

How do I logically separate my queries - or at least not have all my queries in the Query class.

回答1:

If you want to completely separate user-related queries from organization-related queries, then:

  1. Split single .graphqls file into separate files:

user.graphqls:

    schema {
        query: Query
        mutation: Mutation
    }
    type Query {
        fetchUser(email: String): User
    }
    ...

organization.graphqls:

    schema {
        query: Query
        mutation: Mutation
    }
    type Query {
        listOrganizations(max: Int): [GenericListing]
    }
    ...
  1. Split resolvers:
    @Component
    public class UserQuery implements GraphQLQueryResolver {
        public User fetchUser(String email) {
            ...
        }
    }
    @Component
    public class OrganizationQuery implements GraphQLQueryResolver {
        public List<GenericListing> listOrganisations(Integer max) {
            ...
        }
    }

Also, you can use graphql-java-codegen plugin for auto-generating interfaces and data classes based on your schemas. By the way, it supports multiple schema files:

  • Gradle plugin: graphql-java-codegen-gradle-plugin
  • Maven plugin: grapqhl-java-codegen-maven-plugin