Skip to content

Repository files navigation

GraphQL Spring Handler Method

Overview

graphql-spring-handler-method is a library that allows GraphQL to utilize HandlerMethod, similar to how MVC interceptors use HandlerMethod.

Installation

To use this library, add the following dependency to your pom.xml (for Maven):

<dependency>
<groupId>io.github.graphql-spring</groupId>
<artifactId>graphql-spring-handler-method</artifactId>
<version>1.0.0</version>
</dependency>

For Gradle:

dependencies {
implementation 'io.github.graphql-spring:graphql-spring-handler-method:1.0.0'
}

Usage

Configuration

Add the handler mapping bean to your Spring configuration.

@ConfigurationpublicclassGraphqlInterceptorConfig {
@BeanpublicGraphqlHandlerMappinggraphqlHandlerMapping(ApplicationContextapplicationContext) {
returnnewGraphqlHandlerMapping(applicationContext);
}
}

Example

You can manage annotation-based logic in GraphQL interceptors like the example below.

TestAnnotation
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documentedpublic @interface TestAnnotation {
}
TestController
@ControllerpublicclassTestController {
@TestAnnotation@MutationMappingpublicStringtest(@ArgumentTestInputinput) {
return"test";
}
}
TestInterceptor
@Slf4j@Configuration@RequiredArgsConstructorpublicclassTestInterceptorimplementsWebGraphQlInterceptor {
privatefinalGraphqlHandlerMappinghandlerMapping;
@OverridepublicMono<WebGraphQlResponse> intercept(WebGraphQlRequestrequest, Chainchain) {
List<String> requestedFields = extractRequestedFields(request);
for (StringfieldName : requestedFields) {
GraphqlHandlerMethodhandlerMethod = handlerMapping.getHandlerMethod(fieldName);
if (handlerMethod != null) {
if (handlerMethod.hasMethodAnnotation(TestAnnotation.class)) {
log.warn("TestAnnotation Annotation Detected: " + fieldName);
//In the example, this log will be printed.
}
// Add Your Custom Annotation
}
}
returnchain.next(request);
}
privateList<String> extractRequestedFields(WebGraphQlRequestrequest) {
StringdocumentString = request.getDocument();
Documentdocument = newParser().parseDocument(documentString);
returndocument.getDefinitions().stream()
.filter(OperationDefinition.class::isInstance) .map(OperationDefinition.class::cast)
.filter(op -> op.getName() == null || op.getName().equals(request.getOperationName())) .flatMap(op -> op.getSelectionSet().getSelections().stream()) .filter(Field.class::isInstance) .map(Field.class::cast)
.map(Field::getName)
.collect(Collectors.toList());
}
}

About

graphql-spring-handler-method is a library that allows GraphQL to utilize HandlerMethod, similar to how MVC interceptors use HandlerMethod.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages