Skip to main content
Version: 8.x.x

Generating GraphQL Context

graphql-kotlin-ktor-server provides a Ktor specific implementation of GraphQLContextFactory and the context.

  • KtorGraphQLContextFactory - Generates GraphQL context map with federated tracing information per request

If you are using graphql-kotlin-ktor-server, you should extend DefaultKtorGraphQLContextFactory to automatically support federated tracing.

class CustomGraphQLContextFactory : DefaultKtorGraphQLContextFactory() {
override suspend fun generateContext(request: ApplicationRequest): GraphQLContext =
super.generateContext(request).plus(
mapOf("myCustomValue" to (request.headers["my-custom-header"] ?: "defaultContext"))
)
}

fun Application.graphQLModule() {
install(GraphQL) {
schema {
packages = listOf("com.example")
queries = listOf(...)
}
server {
contextFactory = CustomGraphQLContextFactory()
}
}
routing {
graphQLPostRoute()
}
}

Once your application is configured to build your custom GraphQL context, you can then access it through a data fetching environment argument. While executing the query, data fetching environment will be automatically injected to the function input arguments. This argument will not appear in the GraphQL schema.

For more details, see the Contextual Data Documentation.

Federated Context

If you need federation tracing support, you can set the appropriate configuration properties. The provided DefaultKtorGraphQLContextFactory populates the required information for federated tracing, so as long as you extend this context class you will maintain feature support.