io.javalin.plugin.graphql.graphql.GraphQLRun.kt Maven / Gradle / Ivy
package io.javalin.plugin.graphql.graphql
import graphql.ExceptionWhileDataFetching
import graphql.ExecutionInput
import graphql.ExecutionResult
import graphql.GraphQL
import org.eclipse.jetty.server.handler.ContextHandler
import org.reactivestreams.Publisher
import org.reactivestreams.Subscriber
import java.util.concurrent.CompletableFuture
class GraphQLRun(private val graphql: GraphQL) {
private var context: Any? = null
private var query: String = ""
private var operationName: String? = null
private var variables: Map = emptyMap()
fun withQuery(query: String): GraphQLRun = apply { this.query = query }
fun withVariables(variables: Map): GraphQLRun = apply { this.variables = variables }
fun withOperationName(operationName: String?) = apply { this.operationName = operationName }
fun withContext(context: Any?): GraphQLRun = apply { this.context = context }
fun execute(): CompletableFuture> {
val action = generateAction();
return graphql.executeAsync(action)
.thenApplyAsync { this.getResult(it) }
}
private fun generateAction(): ExecutionInput {
return ExecutionInput.newExecutionInput()
.variables(variables)
.query(query)
.operationName(operationName)
.context(context)
.build()
}
private fun getResult(executionResult: ExecutionResult): MutableMap {
val result = mutableMapOf()
if (executionResult.errors.isNotEmpty()) {
result["errors"] = executionResult.errors.distinctBy {
if (it is ExceptionWhileDataFetching) {
it.exception
} else {
it
}
}
}
try {
result["data"] = executionResult.getData()
} catch (e: Exception) {}
return result
}
fun subscribe(subscriber: Subscriber): Unit {
val action = generateAction()
return graphql
.execute(action)
.getData>()
.subscribe(subscriber)
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy