Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow spring data repositories to be exposed through GraphQL. #115

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,70 @@ or
return new UserService(...);
}
```
### Repository interfaces extending Repository<T, ID>
Spring Data beans found through scanning based on `@EnableJpaRepositories/@EnableR2dbcRepositories` and similar strategies that extend `org.springframework.data.repository.Repository<T, ID>` are supported with the `SpringDataRepositoryResolverBuilder.class`. Both the default and custom methods are supported as illustrated in the following interface.

```java
@GraphQLApi
@WithResolverBuilder(SpringDataRepositoryResolverBuilder.class)
public interface ItemRepository extends R2dbcRepository<Item, Long> {
Flux<Item> findAllByName(String name);

@Modifying
@Query("UPDATE item SET name = :name where id = :id")
Mono<Integer> updateNameById(String name, Long id);

}

@Data
public class Item implements Persistable<Long> {
@Id
@GraphQLQuery(description = "Item identifier")
Long id;
@GraphQLQuery(description = "Item name")
String name;

@Override
@JsonIgnore
@GraphQLIgnore
public boolean isNew() {
return id == null;
}
}
```

By convention repository methods will be categorized or discarded in the following ways:
1. Methods with `org.reactivestreams.Publisher/org.springframework.data.domain.Example` parameters are discarded.
1. Mutations are defined as methods containing delete, save or update.
1. Queries are methods that remain.
1. Subscriptions are not supported.

Method names are altered to avoid collisions between multiple repositories. The repository type parameter is used to make each method exposed as a GraphQL operation unique. If the type were Item then here are some example names for queries and mutations:

#### Queries

* ItemExistsById(...): [Boolean]
* findAllItemsSorted(...): [Item]
* countItems: [Long]
* findAllItems: [Item]
* findAllItemsById(...): [Item]
* findItemById(...): [Item]

#### Mutations

* saveItem(...): [Item]
* deleteAllItems(...): [Boolean]
* deleteItem(...): [Boolean]
* deleteAllItemsById(...): [Boolean]
* deleteItemById(...): [Boolean]
* saveAllItems(...): [Item]

#### Custom method conventions

It is important to name methods in a similar fashion to the default names to ensure naming is acceptable.

* `Flux<Item> findAllByName(String name)` becomes findAllItemsByName(...): [Item]
* `Mono<Integer> updateNameById(String name, Long id);` becomes updateItemNameById(...): [Int]

## Choosing which methods get exposed through the API

Expand Down
42 changes: 42 additions & 0 deletions graphql-spqr-spring-boot-autoconfigure/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,48 @@
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-r2dbc</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-h2</artifactId>
<scope>test</scope>
</dependency>

</dependencies>

<build>

<plugins>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<executions>
<execution>
<id>allow ItemRepository parameter names</id>
<goals>
<goal>testCompile</goal>
</goals>
<configuration>
<parameters>true</parameters>
</configuration>
</execution>
</executions>
</plugin>

</plugins>

</build>

</project>
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
import io.leangen.graphql.module.Module;
import io.leangen.graphql.spqr.spring.annotations.GraphQLApi;
import io.leangen.graphql.spqr.spring.annotations.WithResolverBuilder;
import io.leangen.graphql.spqr.spring.annotations.WithResolverBuilders;
import io.leangen.graphql.spqr.spring.modules.data.SpringDataRepositoryResolverBuilder;
import io.leangen.graphql.util.Utils;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
Expand All @@ -45,9 +47,13 @@
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.core.type.StandardMethodMetadata;

import java.lang.annotation.Annotation;
Expand Down Expand Up @@ -137,6 +143,41 @@ public BeanResolverBuilder defaultBeanResolverBuilder() {
return (BeanResolverBuilder) new BeanResolverBuilder().withMethodInvokerFactory(aopAwareFactory);
}

@Bean
@ConditionalOnMissingBean
@Conditional(UsesSpringDataRepositoryResolverBuilderWithResolverBuilder.class)
public SpringDataRepositoryResolverBuilder defaultSpringDataRepositoryResolverBuilder() {
return (SpringDataRepositoryResolverBuilder) new SpringDataRepositoryResolverBuilder().withMethodInvokerFactory(aopAwareFactory);
}

private static class UsesSpringDataRepositoryResolverBuilderWithResolverBuilder implements Condition {

@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
boolean answer = true;
for (String beanName : context.getBeanFactory().getBeanNamesForAnnotation(WithResolverBuilder.class)) {
answer = answer && hasSpringDataRepositoryResolverBuilder(
context.getBeanFactory().findAnnotationOnBean(beanName, WithResolverBuilder.class));
}
if (answer) {
for (String beanName : context.getBeanFactory().getBeanNamesForAnnotation(WithResolverBuilders.class)) {
answer = answer && hasSpringDataRepositoryResolverBuilder(
context.getBeanFactory().findAnnotationOnBean(beanName, WithResolverBuilders.class).value());
}
}
return answer;
}

private boolean hasSpringDataRepositoryResolverBuilder(WithResolverBuilder... builders) {
for (WithResolverBuilder builder : builders) {
if (SpringDataRepositoryResolverBuilder.class.equals(builder.value())) {
return true;
}
}
return false;
}
}

@Bean
@ConditionalOnMissingBean
public PublicResolverBuilder defaultPublicResolverBuilder() {
Expand Down Expand Up @@ -351,6 +392,8 @@ private Map<String, SpqrBean> findGraphQLApiComponents() {
//Sanity check only -- should never happen
&& !originatingBeanDefinition.getBeanClassName().startsWith("org.springframework.")) {
beanType = GenericTypeReflector.annotate(resolvableType.getType());
} else if (resolvableType == ResolvableType.NONE && originatingBeanDefinition.getBeanClassName().startsWith("org.springframework.data.")) {
beanType = GenericTypeReflector.annotate(context.getType(beanName));
} else {
beanType = GenericTypeReflector.annotate(AopUtils.getTargetClass(context.getBean(beanName)));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package io.leangen.graphql.spqr.spring.modules.data;

import io.leangen.graphql.metadata.OperationArgument;
import io.leangen.graphql.metadata.Resolver;
import io.leangen.graphql.metadata.strategy.query.PropertyOperationInfoGenerator;
import io.leangen.graphql.metadata.strategy.query.PublicResolverBuilder;
import io.leangen.graphql.metadata.strategy.query.ResolverBuilderParams;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.reactivestreams.Publisher;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.Repository;

public class SpringDataRepositoryResolverBuilder extends PublicResolverBuilder {
public SpringDataRepositoryResolverBuilder(String... basePackages) {
super(basePackages);
this.operationInfoGenerator = new PropertyOperationInfoGenerator();
}

@Override
protected boolean isQuery(Method method, ResolverBuilderParams params) {
return super.isQuery(method, params) && inputNotPublisherOrExample(method);
}

private boolean inputNotPublisherOrExample(Method method) {
for (Class<?> cls : method.getParameterTypes()) {
if (Publisher.class.isAssignableFrom(cls) || Example.class.isAssignableFrom(cls)) {
return false;
}
}
return true;
}

@Override
protected boolean isMutation(Method method, ResolverBuilderParams params) {
String name = method.getName(); // Spring data repository naming conventions assumed
return (name.contains("delete") || name.contains("save") || name.contains("update"))
&& inputNotPublisherOrExample(method);
}

@Override
protected boolean isSubscription(Method method, ResolverBuilderParams params) {
return false;
}

@Override
protected boolean isPackageAcceptable(Member method, ResolverBuilderParams params) {
return true; // This ResolverBuilder is opted into through annotation, wherever it is used, it is valid
}

@Override
public Collection<Resolver> buildQueryResolvers(ResolverBuilderParams params) {
return renameOperations(super.buildQueryResolvers(params), params);
}

@Override
public Collection<Resolver> buildMutationResolvers(ResolverBuilderParams params) {
return renameOperations(super.buildMutationResolvers(params), params);
}

@Override
public Collection<Resolver> buildSubscriptionResolvers(ResolverBuilderParams params) {
return renameOperations(super.buildSubscriptionResolvers(params), params);
}

private Collection<Resolver> renameOperations(Collection<Resolver> resolvers, ResolverBuilderParams params) {
Type repositoryResourceType = dataRepositoryType(params);
return repositoryResourceType == null ? resolvers
: resolvers.stream().map(r -> renameOperation(r, repositoryResourceType)).collect(Collectors.toList());
}

private Type dataRepositoryType(ResolverBuilderParams params) {
for (Type t : params.getExposedBeanType().getGenericInterfaces()) {
if (ParameterizedType.class.isAssignableFrom(t.getClass())
&& Repository.class.isAssignableFrom((Class<?>) ((ParameterizedType) t).getRawType())) {
return ((ParameterizedType) t).getActualTypeArguments()[0];
}
}
return null;
}

private Resolver renameOperation(Resolver original, Type repositoryResourceType) {
String name = original.getOperationName(), typeName = ((Class<?>) repositoryResourceType).getSimpleName();
if (name.startsWith("exists")) {
name = name.replace("exists", typeName + "Exists");
} else if (name.contains("All")) {
name = name.replace("All", "All" + typeName + "s");
} else if (name.startsWith("find")) {
name = name.replace("find", "find" + typeName);
} else if (name.startsWith("delete")) {
name = name.replace("delete", "delete" + typeName);
} else if (name.startsWith("update")) {
name = name.replace("update", "update" + typeName);
} else if (name.equals("count")) {
name = name.replace("count", "count" + typeName + "s");
} else {
name += typeName;
}
if (isSorted(original.getArguments())) {
name += "Sorted";
}
return new Resolver(name, original.getOperationDescription(), original.getOperationDeprecationReason(),
original.isBatched(), original.getExecutable(), original.getTypedElement(), original.getArguments(),
original.getComplexityExpression());
}

private boolean isSorted(List<OperationArgument> arguments) {
return arguments.stream().filter(a -> Sort.class.isAssignableFrom(a.getParameter().getType())).count() > 0;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package io.leangen.graphql.spqr.spring.modules.data;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories;

@SpringBootApplication
@EnableR2dbcRepositories(basePackageClasses = Application.class)
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package io.leangen.graphql.spqr.spring.modules.data;

import com.fasterxml.jackson.annotation.JsonIgnore;
import io.leangen.graphql.annotations.GraphQLIgnore;
import io.leangen.graphql.annotations.GraphQLQuery;
import org.springframework.data.annotation.Id;
import org.springframework.data.domain.Persistable;

public class Item implements Persistable<Long> {
@Id
@GraphQLQuery(description = "Item identifier")
Long id;
@GraphQLQuery(description = "Item name")
String name;

@Override
public Long getId() {
return id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public void setId(Long id) {
this.id = id;
}

@Override
@JsonIgnore
@GraphQLIgnore
public boolean isNew() {
return id == null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package io.leangen.graphql.spqr.spring.modules.data;

import io.leangen.graphql.spqr.spring.annotations.GraphQLApi;
import io.leangen.graphql.spqr.spring.annotations.WithResolverBuilder;
import org.springframework.data.r2dbc.repository.Modifying;
import org.springframework.data.r2dbc.repository.Query;
import org.springframework.data.r2dbc.repository.R2dbcRepository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@GraphQLApi
@WithResolverBuilder(SpringDataRepositoryResolverBuilder.class)
public interface ItemRepository extends R2dbcRepository<Item, Long> {
Flux<Item> findAllByName(String name);

@Modifying
@Query("UPDATE item SET name = :name where id = :id")
Mono<Integer> updateNameById(String name, Long id);

}
Loading