forked from neo4j-graphql/neo4j-graphql-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataFetcherInterceptorDemo.kt
More file actions
62 lines (54 loc) · 2.11 KB
/
DataFetcherInterceptorDemo.kt
File metadata and controls
62 lines (54 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package demo
import graphql.GraphQL
import graphql.language.VariableReference
import graphql.schema.*
import org.intellij.lang.annotations.Language
import org.neo4j.driver.v1.AuthTokens
import org.neo4j.driver.v1.GraphDatabase
import org.neo4j.graphql.Cypher
import org.neo4j.graphql.DataFetchingInterceptor
import org.neo4j.graphql.SchemaBuilder
import java.math.BigDecimal
import java.math.BigInteger
fun initBoundSchema(schema: String): GraphQLSchema {
val driver = GraphDatabase.driver("bolt://localhost", AuthTokens.basic("neo4j", "test"))
val dataFetchingInterceptor = object : DataFetchingInterceptor {
override fun fetchData(env: DataFetchingEnvironment, delegate: DataFetcher<Cypher>): Any? {
val cypher = delegate.get(env)
return driver.session().use { session ->
val result = session.run(cypher.query, cypher.params.mapValues { toBoltValue(it.value, env.variables) })
val key = result.keys().stream().findFirst().orElse(null)
if (isListType(cypher.type)) {
result.list().map { record -> record.get(key).asObject() }
} else {
result.list().map { record -> record.get(key).asObject() }
.firstOrNull() ?: emptyMap<String, Any>()
}
}
}
}
return SchemaBuilder.buildSchema(schema, dataFetchingInterceptor = dataFetchingInterceptor)
}
fun main() {
@Language("GraphQL") val schema = initBoundSchema("""
type Movie {
movieId: ID!
title: String
}
""".trimIndent())
val graphql = GraphQL.newGraphQL(schema).build()
val movies = graphql.execute("{ movie { title }}")
}
fun toBoltValue(value: Any?, params: Map<String, Any?>) = when (value) {
is VariableReference -> params[value.name]
is BigInteger -> value.longValueExact()
is BigDecimal -> value.toDouble()
else -> value
}
private fun isListType(type: GraphQLType?): Boolean {
return when (type) {
is GraphQLType -> true
is GraphQLNonNull -> isListType(type.wrappedType)
else -> false
}
}