首页 > 解决方案 > graphql-java 12.0 中的 GraphqlFieldVisibility

问题描述

我有一个使用 Spring Boot 运行的项目,并使用 com.graphql-java.graphql-java:12.0 实现了一个 GraphQL API。

我现在想为一些 Mutators 和一些字段设置字段可见性,但不幸的是,我找不到任何教程、文档或示例,我可以在其中找到如何做到这一点的有效解释。

为了解释,我在架构中有以下示例条目:

type Query {
    login(username: String!, password: String!): String
    organization(id: Int!): ApiOrganization
}

type Mutation {
    updateProfile(profileData: ProfileInputDto): ID
    updateAdminStuff(adminData: AdminStuffDto): ID
}

对于使用 api 的所有用户,查询条目现在应该在模式中可见,并且 updateProfile 的突变也应该可见。但是只有当用户以管理员角色登录时,突变 updateAdminStuff 才可见,因此普通用户甚至不知道这个突变的存在。此外,可能只有某些模式类型的某些字段仅对某些角色可见。

我发现有机会通过 GraphqlFieldVisibility ( https://www.graphql-java.com/documentation/v12/fieldvisibility/ ) 设置类似的东西。我发现的第一个版本说要在 GraphQLSchema 中设置它,但它似乎已被弃用,我应该使用 GraphQLCodeRegistry 来设置可见性。对于 GraphQLCodeRegistry,我在https://www.graphql-java.com/documentation/v12/execution/上找到了

GraphQLCodeRegistry codeRegistry = newCodeRegistry()
            .dataFetcher(
                    coordinates("CreateReviewForEpisodeMutation", "createReview"),
                    mutationDataFetcher()
            )
            .build();


GraphQLSchema schema = GraphQLSchema.newSchema()
        .query(queryType)
        .mutation(createReviewForEpisodeMutation)
        .codeRegistry(codeRegistry)
        .build();

但不幸的是,我找不到为我使用的模式生成设置此方法的方法。

有人可以给我一个提示(例如,教程,文档),我可以在哪里找到解决方案的提示?(如果在 GraphQL 中完全有可能)

这里有一些关于项目的附加信息:我有一个 schmea 定义保存为 schema.graphqls。我有一个 GraphQLProvider,它通过以下方式准备了 Scehma 和 GraphQL:

    private GraphQL graphQL;

@Bean
public GraphQL graphQL() {
    return graphQL;
}
@PostConstruct
public void init() throws IOException {
    URL url = Resources.getResource("graphql/schema.graphqls");
    String sdl = Resources.toString(url, Charsets.UTF_8);
    GraphQLSchema graphQLSchema = buildSchema(sdl);
    this.graphQL = GraphQL.newGraphQL(graphQLSchema).build();
}

private GraphQLSchema buildSchema(String sdl) {
    TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(sdl);
    RuntimeWiring runtimeWiring = buildWiring();
    SchemaGenerator schemaGenerator = new SchemaGenerator();
    return schemaGenerator.makeExecutableSchema(typeRegistry, runtimeWiring);
}

在我的控制器中,我通过以下方式获取数据

ExecutionInput executionInput = ExecutionInput.newExecutionInput().context(request).query(body.getQuery())
          .build();
    ExecutionResult executionResult = graphQL.execute(executionInput);

其中 body 是 GraphQLQuery 而 graphQL 是之前代码的 bean。

感谢您的帮助和最诚挚的问候。

标签: javagraphql

解决方案


好的,在 GraphQL-Java 聊天中得到了答案。

我使用本教程https://www.graphql-java.com/tutorials/getting-started-with-spring-boot/来构建 graphQl API,并使用它自己构建运行时接线,在那里我可以设置可见性.

我现在以这种方式实现它:

GraphqlFieldVisibility blockedFields = BlockedFields.newBlock()
      .addPattern("ApiField.secretfield")
      .addPattern(".*\\.secretAdminMutation") 
      .build();

private RuntimeWiring buildWiring() {
    return RuntimeWiring.newRuntimeWiring().fieldVisibility(blockedFields)....

效果很好!


推荐阅读