Skip to content

[ktor server] simplify KtorGraphQLRequestParser #1704

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
Mar 8, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import com.fasterxml.jackson.databind.type.MapType
import com.fasterxml.jackson.databind.type.TypeFactory
import io.ktor.http.HttpMethod
import io.ktor.server.request.ApplicationRequest
import io.ktor.server.request.receiveText
import io.ktor.server.request.receive
import java.io.IOException

internal const val REQUEST_PARAM_QUERY = "query"
Expand All @@ -39,7 +39,6 @@ class KtorGraphQLRequestParser(
) : GraphQLRequestParser<ApplicationRequest> {

private val mapTypeReference: MapType = TypeFactory.defaultInstance().constructMapType(HashMap::class.java, String::class.java, Any::class.java)
// private val graphQLContentType: ContentType = ContentType.parse("application/graphql-response+json")

override suspend fun parseRequest(request: ApplicationRequest): GraphQLServerRequest? = when (request.local.method) {
HttpMethod.Get -> parseGetRequest(request)
Expand All @@ -61,9 +60,8 @@ class KtorGraphQLRequestParser(
}

private suspend fun parsePostRequest(request: ApplicationRequest): GraphQLServerRequest? = try {
val rawRequest = request.call.receiveText()
mapper.readValue(rawRequest, GraphQLServerRequest::class.java)
request.call.receive()
Copy link
Contributor

@samuelAndalon samuelAndalon Mar 8, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how does the ApplicationRequest instance know to which type the request payload needs to be deserialized to ? is it an inlineClass ?

request.call.receive<GraphQLServerRequest>()

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

type inference from the method return type -> since Jackson content negotiation is installed on the route it will deserialize it to appropriate GraphQLServerRequest (single or batch)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and yes receive is inline reified method

} catch (e: IOException) {
throw IllegalStateException("Invalid HTTP request - unable to parse GraphQL request from POST payload")
throw IllegalStateException("Invalid HTTP request - unable to parse GraphQL request from POST payload", e)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.expediagroup.graphql.server.ktor

import com.expediagroup.graphql.server.operations.Query
import com.expediagroup.graphql.server.types.GraphQLBatchRequest
import com.expediagroup.graphql.server.types.GraphQLRequest
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.get
Expand All @@ -38,7 +39,7 @@ import kotlin.test.assertEquals
class GraphQLPluginTest {

class TestQuery : Query {
fun hello(name: String?): String = if (name == null) {
fun hello(name: String? = null): String = if (name == null) {
"Hello World"
} else {
"Hello $name"
Expand Down Expand Up @@ -135,6 +136,30 @@ class GraphQLPluginTest {
}
}

@Test
fun `server should handle valid POST batch requests`() {
testApplication {
val client = createClient {
install(ContentNegotiation) {
jackson()
}
}
val response = client.post("/graphql") {
contentType(ContentType.Application.Json)
setBody(
GraphQLBatchRequest(
listOf(
GraphQLRequest(query = "query HelloWorldQuery { hello }"),
GraphQLRequest(query = "query HelloQuery(\$name: String){ hello(name: \$name) }", operationName = "HelloQuery", variables = mapOf("name" to "junit"))
)
)
)
}
assertEquals(HttpStatusCode.OK, response.status)
assertEquals("""[{"data":{"hello":"Hello World"}},{"data":{"hello":"Hello junit"}}]""", response.bodyAsText().trim())
}
}

@Test
fun `server should return Bad Request for invalid POST requests`() {
testApplication {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import io.ktor.http.HttpMethod
import io.ktor.server.request.ApplicationRequest
import io.ktor.server.testing.TestApplicationRequest
import io.ktor.utils.io.ByteReadChannel
import io.mockk.coEvery
import io.mockk.every
import io.mockk.mockk
Expand Down Expand Up @@ -93,7 +92,7 @@ class KtorGraphQLRequestParserTest {
val serverRequest = mockk<TestApplicationRequest>(relaxed = true) {
every { call } returns mockk(relaxed = true) {
every { attributes.getOrNull<Any>(any()) } returns null
coEvery { request.pipeline.execute(any(), any()) } returns ByteReadChannel(mapper.writeValueAsBytes(mockRequest))
coEvery { request.pipeline.execute(any(), any()) } returns mockRequest
}
every { local.method } returns HttpMethod.Post
}
Expand All @@ -115,7 +114,7 @@ class KtorGraphQLRequestParserTest {
val serverRequest = mockk<TestApplicationRequest>(relaxed = true) {
every { call } returns mockk(relaxed = true) {
every { attributes.getOrNull<Any>(any()) } returns null
coEvery { request.pipeline.execute(any(), any()) } returns ByteReadChannel(mapper.writeValueAsBytes(mockRequest))
coEvery { request.pipeline.execute(any(), any()) } returns mockRequest
}
every { local.method } returns HttpMethod.Post
}
Expand All @@ -138,8 +137,3 @@ class KtorGraphQLRequestParserTest {
assertNull(secondRequest.variables)
}
}

/*
@Suppress("BlockingMethodInNonBlockingContext")

*/