forked from neo4j-graphql/neo4j-graphql-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataFetcherInterceptorDemo.kt
60 lines (52 loc) · 2.01 KB
/
DataFetcherInterceptorDemo.kt
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
package demo
import graphql.GraphQL
import graphql.schema.*
import org.intellij.lang.annotations.Language
import org.neo4j.cypherdsl.core.renderer.Dialect
import org.neo4j.driver.AuthTokens
import org.neo4j.driver.Driver
import org.neo4j.driver.GraphDatabase
import org.neo4j.graphql.*
import java.math.BigDecimal
import java.math.BigInteger
fun initBoundSchema(schema: String): GraphQLSchema {
val driver: Driver = GraphDatabase.driver("bolt://localhost", AuthTokens.basic("neo4j", "test"))
val dataFetchingInterceptor = object : DataFetchingInterceptor {
override fun fetchData(env: DataFetchingEnvironment, delegate: DataFetcher<Cypher>): Any {
env.graphQlContext.setQueryContext(QueryContext(neo4jDialect = Dialect.DEFAULT))
val (cypher, params, type, variable) = delegate.get(env)
return driver.session().use { session ->
val result = session.run(cypher, params.mapValues { toBoltValue(it.value) })
if (isListType(type)) {
result.list().map { record -> record.get(variable).asObject() }
} else {
result.list().map { record -> record.get(variable).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?) = when (value) {
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
}
}