如何添加自定义架构指令Spring Boot GraphQL APP

时间:2018-12-02 23:19:51

标签: graphql graphql-java graphql-spring-boot

我创建了一个客户SchemaDirective并尝试将其注册到使用

的Spring Boot应用程序中
    <dependency>
        <groupId>com.graphql-java</groupId>
        <artifactId>graphql-spring-boot-starter</artifactId>
        <version>5.0.2</version>
    </dependency>

和GraphQLQueryResolver

公共类AuthorizationDirective实现SchemaDirectiveWiring {

@Override
public GraphQLFieldDefinition onField(SchemaDirectiveWiringEnvironment<GraphQLFieldDefinition> schemaDirectiveWiringEnv) {
    String targetAuthRole = (String) schemaDirectiveWiringEnv.getDirective().getArgument("role").getValue();

    GraphQLFieldDefinition field = schemaDirectiveWiringEnv.getElement();
    //
    // build a data fetcher that first checks authorisation roles before then calling the original data fetcher
    //
    DataFetcher originalDataFetcher = field.getDataFetcher();
    DataFetcher authDataFetcher = new DataFetcher() {
        @Override
        public Object get(DataFetchingEnvironment dataFetchingEnvironment) throws Exception {
            Map<String, Object> contextMap = dataFetchingEnvironment.getContext();
            //AuthorisationCtx authContext = (AuthorisationCtx) contextMap.get("authContext");

            if ("dev".equals(targetAuthRole)) {
                return originalDataFetcher.get(dataFetchingEnvironment);
            } else {
                return "Un-Authorized";
            }
        }
    };
    //
    // now change the field definition to have the new authorising data fetcher
    return field.transform(builder -> builder.dataFetcher(authDataFetcher));
}

下面的方法有效,但是当我使用GraphQLQueryResover时,我没有创建任何DataFetchers

private RuntimeWiring buildRuntimeWiring() {
    return RuntimeWiring.newRuntimeWiring().directive("auth", new AuthorisationDirective())
            .type("Query", typeWiring -> typeWiring
                    .dataFetcher("allBooks", allBooksDataFetcher)
                    .dataFetcher("book", bookDataFetcher))
            .build();
}

请在springboot方式中进行注册。

0 个答案:

没有答案