Skip to content

Add example for integrating with new Spring GraphQL #264

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

Merged
merged 1 commit into from
Mar 25, 2022
Merged
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
115 changes: 115 additions & 0 deletions examples/graphql-spring-boot/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0-M1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<groupId>org.neo4j.graphql.examples</groupId>
<artifactId>graphql-spring-boot</artifactId>
<version>1.0-SNAPSHOT</version>

<name>Example - graphql-spring-boot</name>
<description>Example for using neo4j-graphql-java with Spring Boot</description>

<properties>
<java.version>11</java.version>
<testcontainers.version>1.16.2</testcontainers.version>
</properties>

<dependencies>
<!-- spring dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-graphql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- neo4j driver + the neo4j-graphql-java library -->
<dependency>
<groupId>org.neo4j.driver</groupId>
<artifactId>neo4j-java-driver-spring-boot-starter</artifactId>
<version>4.2.7.0</version>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-graphql-java</artifactId>
<version>1.5.1-SNAPSHOT</version>
</dependency>


<!-- Test dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webflux</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.graphql</groupId>
<artifactId>spring-graphql-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>neo4j</artifactId>
<version>${testcontainers.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${testcontainers.version}</version>
<scope>test</scope>
</dependency>
</dependencies>


<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

<repositories>
<!-- TODO remove after release of Spring Boot 2.7 -->
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>

</project>
36 changes: 36 additions & 0 deletions examples/graphql-spring-boot/readme.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
= Example: Integration of Neo4j-GraphQL-Java into a Spring Boot application using Springs GraphQL

== Overview

This example uses the https://docs.spring.io/spring-graphql/docs/1.0.0-SNAPSHOT/reference/html/[Springs new GraphQL library]

In the link:src/main/java/org/neo4j/graphql/examples/graphqlspringboot/config/Neo4jConfiguration.java[Neo4jConfiguration]
a DataFetchingInterceptor is created, which will be bound to all fields augmented by the neo4j-graphql-library.
Its purpose is the execution of the cypher query and the transformation of the query result.

In the link:src/main/java/org/neo4j/graphql/examples/graphqlspringboot/config/GraphQLConfiguration.java[GraphQLConfiguration]
the type definitions of link:src/main/resources/neo4j.graphql[schema] are loaded and augmented.

In this example some fields of the enhanced type (neo4j) are extended with
link:src/main/java/org/neo4j/graphql/examples/graphqlspringboot/datafetcher/AdditionalDataFetcher.java[custom data fetcher] whose link:src/main/resources/graphql/schema.graphqls[schema is separately defined].

With This in place you can

== Run the example

1. link:src/main/resources/application.yaml[configure your neo4j db] or use a public one
2. run the link:src/main/java/org/neo4j/graphql/examples/graphqlspringboot/GraphqlSpringBootApplication.java[spring boot application]
3. open http://localhost:8080/graphiql to run some graphql queries e.g. try:

```graphql
query{
other
movies (options: {limit: 3}){
title
bar
javaData {
name
}
}
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package org.neo4j.graphql.examples.graphqlspringboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class GraphqlSpringBootApplication {

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

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package org.neo4j.graphql.examples.graphqlspringboot.config;

import graphql.schema.GraphQLCodeRegistry;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import org.neo4j.graphql.DataFetchingInterceptor;
import org.neo4j.graphql.SchemaBuilder;
import org.neo4j.graphql.SchemaConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.graphql.GraphQlSourceBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Configuration
public class GraphQLConfiguration {

@Value("classpath:neo4j.graphql")
public Resource graphQl;

@Autowired(required = false)
public DataFetchingInterceptor dataFetchingInterceptor;

@Bean
public GraphQlSourceBuilderCustomizer graphQlSourceBuilderCustomizer() throws IOException {

String schema = new String(graphQl.getInputStream().readAllBytes(), StandardCharsets.UTF_8);

TypeDefinitionRegistry neo4jTypeDefinitionRegistry = new SchemaParser().parse(schema);
SchemaBuilder schemaBuilder = new SchemaBuilder(neo4jTypeDefinitionRegistry, new SchemaConfig(
new SchemaConfig.CRUDConfig(),
new SchemaConfig.CRUDConfig(false, List.of()),
false, true, SchemaConfig.InputStyle.INPUT_TYPE, true, false));
schemaBuilder.augmentTypes();

return builder -> builder
.configureRuntimeWiring(runtimeWiringBuilder -> {
schemaBuilder.registerTypeNameResolver(runtimeWiringBuilder);
schemaBuilder.registerScalars(runtimeWiringBuilder);
GraphQLCodeRegistry.Builder codeRegistryBuilder = GraphQLCodeRegistry.newCodeRegistry();
schemaBuilder.registerDataFetcher(codeRegistryBuilder, dataFetchingInterceptor);
runtimeWiringBuilder.codeRegistry(codeRegistryBuilder);
})
.schemaFactory((typeDefinitionRegistry, runtimeWiring) -> {
typeDefinitionRegistry.merge(neo4jTypeDefinitionRegistry);
return new SchemaGenerator().makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package org.neo4j.graphql.examples.graphqlspringboot.config;

import graphql.schema.GraphQLList;
import graphql.schema.GraphQLNonNull;
import graphql.schema.GraphQLType;
import org.neo4j.driver.Driver;
import org.neo4j.driver.Result;
import org.neo4j.driver.SessionConfig;
import org.neo4j.graphql.Cypher;
import org.neo4j.graphql.DataFetchingInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
* Configuration of the DataFetchingInterceptor
*/
@Configuration
public class Neo4jConfiguration {

/**
* This interceptor is bound to all the graphql fields generated by the neo4j-graphql-library.
* Its purpose is the execution of the cypher query and the transformation of the query result.
*/
@Bean
public DataFetchingInterceptor dataFetchingInterceptor(
Driver driver,
@Value("${database}") String database) {
return (env, delegate) -> {
Cypher cypher = delegate.get(env);
return driver.session(SessionConfig.forDatabase(database)).writeTransaction(tx -> {
Map<String, Object> boltParams = new HashMap<>(cypher.getParams());
boltParams.replaceAll((key, value) -> toBoltValue(value));

Result result = tx.run(cypher.getQuery(), boltParams);
if (isListType(cypher.getType())) {
return result.list()
.stream()
.map(record -> record.get(cypher.getVariable()).asObject())
.collect(Collectors.toList());
} else {
return result.list()
.stream()
.map(record -> record.get(cypher.getVariable()).asObject())
.collect(Collectors.toList())
.stream().findFirst()
.orElse(Collections.emptyMap());
}
});
};
}

private Object toBoltValue(Object value) {
if (value instanceof BigInteger) {
return ((BigInteger) value).longValueExact();
}
if (value instanceof BigDecimal) {
return ((BigDecimal) value).doubleValue();
}
return value;
}

private boolean isListType(GraphQLType type) {
if (type instanceof GraphQLList) {
return true;
}
return type instanceof GraphQLNonNull
&& this.isListType(((GraphQLNonNull) type).getWrappedType());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package org.neo4j.graphql.examples.graphqlspringboot.datafetcher;

import com.fasterxml.jackson.annotation.JsonProperty;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.graphql.data.method.annotation.SchemaMapping;
import org.springframework.stereotype.Controller;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@Controller
class AdditionalDataFetcher {

@SchemaMapping(typeName = "Movie", field = "bar")
public String bar() {
return "foo";
}

@SchemaMapping(typeName = "Movie", field = "javaData")
public List<JavaData> javaData(DataFetchingEnvironment env) {
//noinspection unchecked
Object title = ((Map<String, Object>) env.getSource()).get("title");
return Collections.singletonList(new JavaData("test " + title));
}

@QueryMapping
public String other() {
return "other";
}

public static class JavaData {
@JsonProperty("name")
public String name;

public JavaData(String name) {
this.name = name;
}
}
}
17 changes: 17 additions & 0 deletions examples/graphql-spring-boot/src/main/resources/application.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
org :
neo4j :
driver :
uri : bolt://demo.neo4jlabs.com:7687
authentication :
username : movies
password : movies
config :
encrypted : true
database : movies
spring :
graphql :
schema :
printer :
enabled : true
graphiql :
enabled : true
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
extend type Movie {
bar: String @ignore
javaData: [JavaData!] @ignore
}

type JavaData {
name: String
}

extend type Query {
other: String
}
3 changes: 3 additions & 0 deletions examples/graphql-spring-boot/src/main/resources/neo4j.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
type Movie {
title: String
}
Loading