如何使用Spring Boot GraphQL在逻辑上拆分GraphQL模式和解析器

时间:2019-07-02 16:27:18

标签: java spring-boot graphql graphql-java

此刻,我所有的查询解析器都在单个Query类和单个Query模式/类型下,例如:

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

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

...

我所有的查询都在一个类中:

@Component
public class Query implements GraphQLQueryResolver {

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

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

我已经设法按用户和组织划分并按逻辑划分了我的突变!

@Component
public class UserMutations implements GraphQLMutationResolver {

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

如何在逻辑上分隔查询-或至少不在查询类中包含所有查询。

1 个答案:

答案 0 :(得分:0)

如果要将用户相关查询与组织相关查询完全分开,则:

  1. 将单个.graphqls文件拆分为单独的文件:

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. 拆分解析器:
    @Component
    public class UserQuery implements GraphQLQueryResolver {
        public User fetchUser(String email) {
            ...
        }
    }
    @Component
    public class OrganizationQuery implements GraphQLQueryResolver {
        public List<GenericListing> listOrganisations(Integer max) {
            ...
        }
    }

此外,您可以使用graphql-java-codegen插件根据您的模式自动生成接口和数据类。顺便说一下,它支持多个架构文件: