Skip to content

Use graphql infrastructure to parse requests #247

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
Nov 16, 2021
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
24 changes: 20 additions & 4 deletions core/src/main/kotlin/org/neo4j/graphql/AugmentationHandler.kt
Original file line number Diff line number Diff line change
Expand Up @@ -52,21 +52,35 @@ abstract class AugmentationHandler(
}
return FieldDefinition.newFieldDefinition()
.name("$prefix${resultType.name}")
.inputValueDefinitions(getInputValueDefinitions(scalarFields, forceOptionalProvider))
.inputValueDefinitions(getInputValueDefinitions(scalarFields, false, forceOptionalProvider))
.type(type)
}

protected fun getInputValueDefinitions(
relevantFields: List<FieldDefinition>,
addFieldOperations: Boolean,
forceOptionalProvider: (field: FieldDefinition) -> Boolean): List<InputValueDefinition> {
return relevantFields.map { field ->
return relevantFields.flatMap { field ->
var type = getInputType(field.type)
type = if (forceOptionalProvider(field)) {
(type as? NonNullType)?.type ?: type
} else {
type
}
input(field.name, type)
if (addFieldOperations && !field.isNativeId()) {
val typeDefinition = field.type.resolve()
?: throw IllegalArgumentException("type ${field.type.name()} cannot be resolved")
FieldOperator.forType(typeDefinition, field.type.inner().isNeo4jType())
.map { op ->
val wrappedType: Type<*> = when {
op.list -> ListType(NonNullType(TypeName(type.name())))
else -> type
}
input(op.fieldName(field.name), wrappedType)
}
} else {
listOf(input(field.name, type))
}
}
}

Expand Down Expand Up @@ -280,6 +294,7 @@ abstract class AugmentationHandler(
fun ImplementingTypeDefinition<*>.getFieldDefinition(name: String) = this.fieldDefinitions
.filterNot { it.isIgnored() }
.find { it.name == name }

fun ImplementingTypeDefinition<*>.getIdField() = this.fieldDefinitions
.filterNot { it.isIgnored() }
.find { it.type.inner().isID() }
Expand All @@ -289,7 +304,7 @@ abstract class AugmentationHandler(
fun Type<*>.isNeo4jType(): Boolean = name()
?.takeIf {
!ScalarInfo.GRAPHQL_SPECIFICATION_SCALARS_DEFINITIONS.containsKey(it)
&& it.startsWith("_Neo4j") // TODO remove this check by refactoring neo4j input types
&& it.startsWith("_Neo4j") // TODO remove this check by refactoring neo4j input types
}
?.let { neo4jTypeDefinitionRegistry.getUnwrappedType(it) } != null

Expand All @@ -299,6 +314,7 @@ abstract class AugmentationHandler(
fun FieldDefinition.isNativeId(): Boolean = name == ProjectionBase.NATIVE_ID
fun FieldDefinition.dynamicPrefix(): String? =
getDirectiveArgument(DirectiveConstants.DYNAMIC, DirectiveConstants.DYNAMIC_PREFIX, null)

fun FieldDefinition.isRelationship(): Boolean =
!type.inner().isNeo4jType() && type.resolve() is ImplementingTypeDefinition<*>

Expand Down
1 change: 0 additions & 1 deletion core/src/main/kotlin/org/neo4j/graphql/Cypher.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,4 @@ import graphql.schema.GraphQLType

data class Cypher @JvmOverloads constructor(val query: String, val params: Map<String, Any?> = emptyMap(), var type: GraphQLType? = null, val variable: String) {
fun with(p: Map<String, Any?>) = this.copy(params = this.params + p)
fun escapedQuery() = query.replace("\"", "\\\"").replace("'", "\\'")
}
10 changes: 10 additions & 0 deletions core/src/main/kotlin/org/neo4j/graphql/DynamicProperties.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,16 @@ object DynamicProperties {

@Throws(CoercingParseLiteralException::class)
private fun parse(input: Any, variables: Map<String, Any>): Any? {
return when (input) {
!is Value<*> -> throw CoercingParseLiteralException("Expected AST type 'StringValue' but was '${input::class.java.simpleName}'.")
is NullValue -> null
is ObjectValue -> input.objectFields.map { it.name to parseNested(it.value, variables) }.toMap()
else -> Assert.assertShouldNeverHappen("Only maps structures are expected")
}
}

@Throws(CoercingParseLiteralException::class)
private fun parseNested(input: Any, variables: Map<String, Any>): Any? {
return when (input) {
!is Value<*> -> throw CoercingParseLiteralException("Expected AST type 'StringValue' but was '${input::class.java.simpleName}'.")
is NullValue -> null
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package org.neo4j.graphql

import graphql.GraphQLError

class InvalidQueryException(@Suppress("MemberVisibilityCanBePrivate") val error: GraphQLError) : RuntimeException(error.message)
102 changes: 23 additions & 79 deletions core/src/main/kotlin/org/neo4j/graphql/Translator.kt
Original file line number Diff line number Diff line change
@@ -1,93 +1,37 @@
package org.neo4j.graphql

import graphql.execution.MergedField
import graphql.language.Document
import graphql.language.Field
import graphql.language.FragmentDefinition
import graphql.language.OperationDefinition
import graphql.language.OperationDefinition.Operation.MUTATION
import graphql.language.OperationDefinition.Operation.QUERY
import graphql.parser.InvalidSyntaxException
import graphql.parser.Parser
import graphql.schema.DataFetchingEnvironmentImpl.newDataFetchingEnvironment
import graphql.schema.GraphQLFieldDefinition
import graphql.schema.GraphQLObjectType
import graphql.ExceptionWhileDataFetching
import graphql.ExecutionInput
import graphql.GraphQL
import graphql.InvalidSyntaxError
import graphql.schema.GraphQLSchema
import java.math.BigDecimal
import java.math.BigInteger
import graphql.validation.ValidationError

class Translator(val schema: GraphQLSchema) {

class CypherHolder(var cypher: Cypher?)

private val gql: GraphQL = GraphQL.newGraphQL(schema).build()

@JvmOverloads
@Throws(OptimizedQueryException::class)
fun translate(query: String, params: Map<String, Any?> = emptyMap(), ctx: QueryContext = QueryContext()): List<Cypher> {
val ast = parse(query) // todo preparsedDocumentProvider
val fragments = ast.definitions.filterIsInstance<FragmentDefinition>().associateBy { it.name }
return ast.definitions.filterIsInstance<OperationDefinition>()
.filter { it.operation == QUERY || it.operation == MUTATION } // todo variableDefinitions, directives, name
.flatMap { operationDefinition ->
operationDefinition.selectionSet.selections
.filterIsInstance<Field>() // FragmentSpread, InlineFragment
.map { field ->
val cypher = toQuery(operationDefinition.operation, field, fragments, params, ctx)
val resolvedParams = cypher.params.mapValues { toBoltValue(it.value) }
cypher.with(resolvedParams)
}
}
}

private fun toBoltValue(value: Any?) = when (value) {
is BigInteger -> value.longValueExact()
is BigDecimal -> value.toDouble()
else -> value
}

private fun toQuery(op: OperationDefinition.Operation,
field: Field,
fragments: Map<String, FragmentDefinition?>,
variables: Map<String, Any?>,
ctx: QueryContext = QueryContext()
): Cypher {
val name = field.name
val operationObjectType: GraphQLObjectType
val fieldDefinition: GraphQLFieldDefinition
when (op) {
QUERY -> {
operationObjectType = schema.queryType
fieldDefinition = operationObjectType.getRelevantFieldDefinition(name)
?: throw IllegalArgumentException("Unknown Query $name available queries: " + (operationObjectType.getRelevantFieldDefinitions()).joinToString { it.name })
}
MUTATION -> {
operationObjectType = schema.mutationType
fieldDefinition = operationObjectType.getRelevantFieldDefinition(name)
?: throw IllegalArgumentException("Unknown Mutation $name available mutations: " + (operationObjectType.getRelevantFieldDefinitions()).joinToString { it.name })
val cypherHolder = CypherHolder(null)
val executionInput = ExecutionInput.newExecutionInput()
.query(query)
.variables(params)
.context(ctx)
.localContext(cypherHolder)
.build()
val result = gql.execute(executionInput)
result.errors?.forEach {
when (it) {
is ExceptionWhileDataFetching -> throw it.exception
is ValidationError -> throw InvalidQueryException(it)
is InvalidSyntaxError -> throw InvalidQueryException(it)
}
else -> throw IllegalArgumentException("$op is not supported")
}
val dataFetcher = schema.codeRegistry.getDataFetcher(operationObjectType, fieldDefinition)
?: throw IllegalArgumentException("no data fetcher found for ${op.name.toLowerCase()} $name")


return dataFetcher.get(newDataFetchingEnvironment()
.mergedField(MergedField.newMergedField(field).build())
.parentType(operationObjectType)
.graphQLSchema(schema)
.fragmentsByName(fragments)
.context(ctx)
.localContext(ctx)
.fieldDefinition(fieldDefinition)
.variables(variables)
.build()) as? Cypher
?: throw java.lang.IllegalStateException("not supported")
}

private fun parse(query: String): Document {
try {
val parser = Parser()
return parser.parseDocument(query)
} catch (e: InvalidSyntaxException) {
// todo proper structured error
throw e
}
return listOf(requireNotNull(cypherHolder.cypher))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,16 @@ class AugmentFieldHandler(
fieldBuilder.inputValueDefinition(input(ProjectionBase.ORDER_BY, orderType))
}
}
if (!schemaConfig.useWhereFilter && schemaConfig.query.enabled && !schemaConfig.query.exclude.contains(fieldType.name)) {
// legacy support
val relevantFields = fieldType
.getScalarFields()
.filter { scalarField -> field.inputValueDefinitions.find { it.name == scalarField.name } == null }
.filter { it.dynamicPrefix() == null } // TODO currently we do not support filtering on dynamic properties
getInputValueDefinitions(relevantFields, true, { true }).forEach {
fieldBuilder.inputValueDefinition(it)
}
}
}

val filterFieldName = if (schemaConfig.useWhereFilter) ProjectionBase.WHERE else ProjectionBase.FILTER
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@ import org.neo4j.cypherdsl.core.renderer.Configuration
import org.neo4j.cypherdsl.core.renderer.Renderer
import org.neo4j.graphql.Cypher
import org.neo4j.graphql.SchemaConfig
import org.neo4j.graphql.Translator
import org.neo4j.graphql.aliasOrName
import org.neo4j.graphql.handler.projection.ProjectionBase

/**
* The is a base class for the implementation of graphql data fetcher used in this project
* This is a base class for the implementation of graphql data fetcher used in this project
*/
abstract class BaseDataFetcher(schemaConfig: SchemaConfig) : ProjectionBase(schemaConfig), DataFetcher<Cypher> {

Expand All @@ -38,8 +39,10 @@ abstract class BaseDataFetcher(schemaConfig: SchemaConfig) : ProjectionBase(sche
val params = statement.parameters.mapValues { (_, value) ->
(value as? VariableReference)?.let { env.variables[it.name] } ?: value
}

return Cypher(query, params, env.fieldDefinition.type, variable = field.aliasOrName())
.also {
(env.getLocalContext() as? Translator.CypherHolder)?.apply { this.cypher = it }
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,14 @@ class MergeOrUpdateHandler private constructor(private val merge: Boolean, schem
}

val relevantFields = type.getScalarFields()
val mergeField = buildFieldDefinition("merge", type, relevantFields, nullableResult = false)
val idField = type.getIdField()
?: throw IllegalStateException("Cannot resolve id field for type ${type.name}")

val mergeField = buildFieldDefinition("merge", type, relevantFields, nullableResult = false, forceOptionalProvider = { it != idField })
.build()
addMutationField(mergeField)

val updateField = buildFieldDefinition("update", type, relevantFields, nullableResult = true)
val updateField = buildFieldDefinition("update", type, relevantFields, nullableResult = true, forceOptionalProvider = { it != idField })
.build()
addMutationField(updateField)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class QueryHandler private constructor(schemaConfig: SchemaConfig) : BaseDataFet
val arguments = if (schemaConfig.useWhereFilter) {
listOf(input(WHERE, TypeName(filterTypeName)))
} else {
getInputValueDefinitions(relevantFields, { true }) +
getInputValueDefinitions(relevantFields, true, { true }) +
input(FILTER, TypeName(filterTypeName))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ open class ProjectionBase(
}
if (nodeType is GraphQLInterfaceType
&& !hasTypeName
&& (env.getLocalContext() as? QueryContext)?.queryTypeOfInterfaces == true
&& (env.getContext() as? QueryContext)?.queryTypeOfInterfaces == true
) {
// for interfaces the typename is required to determine the correct implementation
val (pro, sub) = projectField(propertyContainer, variable, Field(TYPE_NAME), nodeType, env, variableSuffix)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package org.neo4j.graphql

import graphql.parser.InvalidSyntaxException
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.DynamicNode
import org.junit.jupiter.api.DynamicTest
Expand All @@ -19,7 +18,7 @@ class TranslatorExceptionTests : AsciiDocTestSuite("translator-tests1.adoc") {
val translator = Translator(SchemaBuilder.buildSchema(schema))
return listOf(
DynamicTest.dynamicTest("unknownType") {
Assertions.assertThrows(IllegalArgumentException::class.java) {
Assertions.assertThrows(InvalidQueryException::class.java) {
translator.translate("""
{
company {
Expand All @@ -30,7 +29,7 @@ class TranslatorExceptionTests : AsciiDocTestSuite("translator-tests1.adoc") {
}
},
DynamicTest.dynamicTest("mutation") {
Assertions.assertThrows(InvalidSyntaxException::class.java) {
Assertions.assertThrows(InvalidQueryException::class.java) {
translator.translate("""
{
createPerson()
Expand Down
Loading