Skip to content

Commit

Permalink
Cleanup and prepare 0.21.0
Browse files Browse the repository at this point in the history
  • Loading branch information
stuebingerb committed Oct 16, 2024
1 parent e042e6c commit 9a7c2fc
Show file tree
Hide file tree
Showing 44 changed files with 232 additions and 178 deletions.
10 changes: 5 additions & 5 deletions README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

[![Maven Central](https://img.shields.io/maven-central/v/de.stuebingerb/kgraphql.svg?label=Maven%20Central)](https://search.maven.org/search?q=g:%22de.stuebingerb%22%20AND%20a:%22kgraphql%22)

KGraphQL is a [Kotlin](https://kotlinlang.org/) implementation of [GraphQL](http://graphql.org/). It provides a rich DSL
to set up the GraphQL schema.
KGraphQL is a [Kotlin](https://kotlinlang.org/) implementation of [GraphQL](http://graphql.org/) based
on https://github.com/aPureBase/KGraphQL. It provides a rich DSL to set up the GraphQL schema.

```kotlin
data class Article(val id: Int, val text: String)
Expand Down Expand Up @@ -45,7 +45,7 @@ All contributions are welcome. Feel free to open issues and PRs!

## Building

To build KGraphQL you only need to have JDK8 installed. invoke
To build KGraphQL you only need to have JDK 11 installed. Invoke

```bash
./gradlew build
Expand All @@ -55,11 +55,11 @@ To perform local build.

## Versioning

The versioning is following [Semantic Versioning](http://semver.org/)
The versioning from 1.0.0 on is following [Semantic Versioning](http://semver.org/)

## Links

Specification : http://facebook.github.io/graphql/
Specification: https://spec.graphql.org/

## License

Expand Down
2 changes: 1 addition & 1 deletion buildSrc/src/main/kotlin/library-conventions.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ plugins {
}

group = "de.stuebingerb"
version = "0.20.0"
version = "0.21.0"

kotlin {
jvmToolchain(11)
Expand Down
6 changes: 5 additions & 1 deletion kgraphql/src/main/kotlin/com/apurebase/kgraphql/Context.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ class Context(private val map: Map<Any, Any>) {
operator fun <T : Any> get(kClass: KClass<T>): T? {
val value = map[kClass]
@Suppress("UNCHECKED_CAST")
return if (kClass.isInstance(value)) value as T else null
return if (kClass.isInstance(value)) {
value as T
} else {
null
}
}

inline fun <reified T : Any> get(): T? = get(T::class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,10 @@ open class GraphQLError(
val locations: List<Source.LocationSource>? by lazy {
if (positions != null && source != null) {
positions.map { pos -> getLocation(source, pos) }
} else nodes?.mapNotNull { node ->
node.loc?.let { getLocation(it.source, it.start) }
} else {
nodes?.mapNotNull { node ->
node.loc?.let { getLocation(it.source, it.start) }
}
}
}

Expand Down
4 changes: 1 addition & 3 deletions kgraphql/src/main/kotlin/com/apurebase/kgraphql/KGraphQL.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ import com.apurebase.kgraphql.schema.dsl.SchemaBuilder
class KGraphQL {
companion object {
fun schema(init: SchemaBuilder.() -> Unit): Schema {
return SchemaBuilder()
.apply(init)
.build()
return SchemaBuilder().apply(init).build()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class CachingDocumentParser(cacheMaximumSize: Long = 1000L) {
is Result.Exception -> throw result.exception
else -> {
cache.invalidateAll()
throw IllegalStateException("Internal error of CachingDocumentParser")
error("Internal error of CachingDocumentParser")
}
}
}
Expand Down
71 changes: 40 additions & 31 deletions kgraphql/src/main/kotlin/com/apurebase/kgraphql/request/Lexer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@ data class Lexer(
val nextToken = readToken(token)
token.next = nextToken
nextToken
} else token.next!!
} else {
token.next!!
}
} while (token.kind === COMMENT)
}
return token
Expand Down Expand Up @@ -128,7 +130,9 @@ data class Lexer(
// .
46 -> if (body.getOrNull(pos + 1)?.code == 46 && body.getOrNull(pos + 2)?.code == 46) {
tok(SPREAD, start = pos, end = pos + 3)
} else fail(code)
} else {
fail(code)
}
// :
58 -> tok(COLON)
// =
Expand All @@ -150,10 +154,10 @@ data class Lexer(
// - 0-9
45, in (48..57) -> readNumber(pos, code, col, prev)
// "
34 -> {
if (body.getOrNull(pos + 1)?.code == 34 && body.getOrNull(pos + 2)?.code == 34)
readBlockString(pos, col, prev)
else readString(pos, col, prev)
34 -> if (body.getOrNull(pos + 1)?.code == 34 && body.getOrNull(pos + 2)?.code == 34) {
readBlockString(pos, col, prev)
} else {
readString(pos, col, prev)
}

else -> fail(code)
Expand Down Expand Up @@ -361,7 +365,9 @@ data class Lexer(
while (position < body.length) {
code = body.getOrNull(position)?.code ?: break
// not LineTerminator
if (code == 0x00a || code == 0x00d) break
if (code == 0x00a || code == 0x00d) {
break
}

// Closing Quote (")
if (code == 34) {
Expand Down Expand Up @@ -543,31 +549,34 @@ data class Lexer(
}

private fun printCharCode(code: Int?) =
if (code == null) EOF.str
else StringBuilder().apply {
append("\"")
when (val char = code.toChar()) {
'\\' -> append("\\\\")
'"' -> append("\\\"")
'\b' -> append("\\b")
'\n' -> append("\\n")
'\r' -> append("\\r")
'\t' -> append("\\t")
else ->
if (code < 0x007f && char > ' ') {
// Refer: https://utf8-chartable.de/unicode-utf8-table.pl?number=128
append(char)
} else {
append("\\u")
val hex = Integer.toHexString(code)
for (i in hex.length..3) {
append('0')
if (code == null) {
EOF.str
} else {
StringBuilder().apply {
append("\"")
when (val char = code.toChar()) {
'\\' -> append("\\\\")
'"' -> append("\\\"")
'\b' -> append("\\b")
'\n' -> append("\\n")
'\r' -> append("\\r")
'\t' -> append("\\t")
else ->
if (code < 0x007f && char > ' ') {
// Refer: https://utf8-chartable.de/unicode-utf8-table.pl?number=128
append(char)
} else {
append("\\u")
val hex = Integer.toHexString(code)
for (i in hex.length..3) {
append('0')
}
append(hex.uppercase())
}
append(hex.uppercase())
}
}
append("\"")
}.toString()
}
append("\"")
}.toString()
}

/**
* Report a message that an unexpected character was encountered.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,10 +133,10 @@ open class Parser {
loc = loc(start)
)
}
val operation = this.parseOperationType()
val operation = parseOperationType()
var name: NameNode? = null
if (peek(NAME)) {
name = this.parseName()
name = parseName()
}
return DefinitionNode.ExecutableDefinitionNode.OperationDefinitionNode(
operation = operation,
Expand Down Expand Up @@ -295,10 +295,10 @@ open class Parser {
*/
private fun parseFragment(parent: SelectionNode?): SelectionNode.FragmentNode {
val start = lexer.token
this.expectToken(SPREAD)
expectToken(SPREAD)

val hasTypeCondition = expectOptionalKeyword("on")
if (!hasTypeCondition && this.peek(NAME)) {
if (!hasTypeCondition && peek(NAME)) {
return SelectionNode.FragmentNode.FragmentSpreadNode(
parent = parent,
name = parseFragmentName(),
Expand Down Expand Up @@ -428,7 +428,7 @@ open class Parser {
*/
private fun parseList(isConst: Boolean): ValueNode.ListValueNode {
val start = lexer.token
val item = { this.parseValueLiteral(isConst) }
val item = { parseValueLiteral(isConst) }

return ValueNode.ListValueNode(
values = any(BRACKET_L, item, BRACKET_R),
Expand Down Expand Up @@ -506,7 +506,7 @@ open class Parser {
loc = loc(start)
)
} else {
type = this.parseNamedType()
type = parseNamedType()
}

if (expectOptionalToken(BANG) != null) {
Expand Down Expand Up @@ -655,7 +655,7 @@ open class Parser {
*/
private fun parseImplementsInterfaces(): MutableList<TypeNode.NamedTypeNode> {
val types = mutableListOf<TypeNode.NamedTypeNode>()
if (this.expectOptionalKeyword("implements")) {
if (expectOptionalKeyword("implements")) {
// Optional leading ampersand
expectOptionalToken(AMP)
do {
Expand Down Expand Up @@ -1084,7 +1084,7 @@ open class Parser {
val nodes = mutableListOf<T>()
do {
nodes.add(parseFn())
} while (this.expectOptionalToken(closeKind) == null)
} while (expectOptionalToken(closeKind) == null)
return nodes
}
return mutableListOf()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ data class TypeReference(
override fun toString(): String = buildString {
if (isList) {
append("[").append(name)
if (!isElementNullable) append("!")
if (!isElementNullable) {
append("!")
}
append("]")
} else {
append(name)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@ data class Variables(
keyNode: ValueNode.VariableNode,
transform: (value: ValueNode) -> Any?
): T? {
val variable = variables?.find { keyNode.name.value == it.variable.name.value }
?: throw IllegalArgumentException("Variable '$${keyNode.name.value}' was not declared for this operation")
val variable = requireNotNull(variables?.firstOrNull { keyNode.name.value == it.variable.name.value }) {
"Variable '$${keyNode.name.value}' was not declared for this operation"
}

val isIterable = kClass.isIterable()

Expand All @@ -45,7 +46,7 @@ data class Variables(
for (element in value as Iterable<*>) {
if (element == null) {
throw GraphQLError(
"Invalid argument value $value from variable $${keyNode.name.value}, expected list with non null arguments",
"Invalid argument value $value from variable $${keyNode.name.value}, expected list with non-null arguments",
keyNode
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,10 @@ interface VariablesJson {
try {
// TODO: Move away from jackson and only depend on kotlinx.serialization
objectMapper.treeToValue<T>(tree, kType.toTypeReference())
} catch (e: GraphQLError) {
throw e
} catch (e: Exception) {
throw if (e is GraphQLError) e
else ExecutionException("Failed to coerce $tree as $kType", key, e)
throw ExecutionException("Failed to coerce $tree as $kType", key, e)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ class DefaultSchema(
)
}

private fun String.isIntrospection() = this.contains("__schema") || this.contains("__type")
private fun String.isIntrospection() = contains("__schema") || contains("__type")

override fun typeByKClass(kClass: KClass<*>): Type? = model.queryTypes[kClass]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package com.apurebase.kgraphql.schema.dsl

import com.apurebase.kgraphql.Context
import com.apurebase.kgraphql.schema.model.PropertyDef
import java.lang.IllegalArgumentException
import kotlin.reflect.KProperty1

class KotlinPropertyDSL<T : Any, R>(
Expand All @@ -22,10 +21,12 @@ class KotlinPropertyDSL<T : Any, R>(
if (parent != null) rule(
parent,
ctx
) else IllegalArgumentException("Unexpected null parent of kotlin property")
) else {
IllegalArgumentException("Unexpected null parent of kotlin property")
}
}

this.accessRuleBlock = accessRuleAdapter
accessRuleBlock = accessRuleAdapter
}

fun toKQLProperty() = PropertyDef.Kotlin(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ class ResolverDSL(val target: Target) {
fun withArgs(block: InputValuesDSL.() -> Unit) {
val inputValuesDSL = InputValuesDSL().apply(block)

target.addInputValues(inputValuesDSL.inputValues.map { inputValue ->
(inputValue.toKQLInputValue())
})
target.addInputValues(
inputValuesDSL.inputValues.map { inputValue ->
inputValue.toKQLInputValue()
}
)
}

inline fun <reified T : Any> returns(): ResolverDSL {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class UnionPropertyDSL<T : Any>(val name: String, block: UnionPropertyDSL<T>.()
block()
}

internal lateinit var functionWrapper: FunctionWrapper<Any?>
private lateinit var functionWrapper: FunctionWrapper<Any?>

lateinit var returnType: TypeID

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ class MutationDSL(
) : AbstractOperationDSL(name) {

internal fun toKQLMutation(): MutationDef<out Any?> {
val function =
functionWrapper ?: throw IllegalArgumentException("resolver has to be specified for mutation [$name]")
val function = requireNotNull(functionWrapper) {
"resolver has to be specified for mutation [$name]"
}

return MutationDef(
name = name,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ class QueryDSL(
) : AbstractOperationDSL(name) {

internal fun toKQLQuery(): QueryDef<out Any?> {
val function =
functionWrapper ?: throw IllegalArgumentException("resolver has to be specified for query [$name]")
val function = requireNotNull(functionWrapper) {
"resolver has to be specified for query [$name]"
}

return QueryDef(
name = name,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ class SubscriptionDSL(
) : AbstractOperationDSL(name) {

internal fun toKQLSubscription(): SubscriptionDef<out Any?> {
val function =
functionWrapper ?: throw IllegalArgumentException("resolver has to be specified for query [$name]")
val function = requireNotNull(functionWrapper) {
"resolver has to be specified for subscription [$name]"
}

return SubscriptionDef(
name = name,
Expand Down
Loading

0 comments on commit 9a7c2fc

Please sign in to comment.