Skip to main content
Version: 3.x.x

Contextual Data

All GraphQL servers have a concept of a "context". A GraphQL context contains metadata that is useful to the GraphQL server, but shouldn't necessarily be part of the GraphQL schema. A prime example of something that is appropriate for the GraphQL context would be trace headers for an OpenTracing system such as Haystack. The GraphQL query does not need the information to perform its function, but the server needs the information to ensure observability.

The contents of the GraphQL context vary across applications and it is up to the GraphQL server developers to decide what it should contain. For Spring based applications, graphql-kotlin-spring-server provides a simple mechanism to build context per query execution through GraphQLContextFactory. Once context factory bean is available in the Spring application context it will then be used in a corresponding ContextWebFilter to populate GraphQL context based on the incoming request and make it available during query execution. See graphql-kotlin-spring-server documentation for additional details

GraphQLContext Interface

The easiest way to specify a context class is to use the GraphQLContext marker interface. This interface does not require any implementations, it is just used to inform the schema generator that this is the class that should be used as the context for every request.


class MyGraphQLContext(val customValue: String) : GraphQLContext

Then you can just use the class as an argument and it will be automatically injected during execution time.


class ContextualQuery {
fun contextualQuery(
context: MyGraphQLContext,
value: Int
): String = "The custom value was ${context.customValue} and the value was $value"
}

The above query would produce the following GraphQL schema:


schema {
query: Query
}

type Query {
contextualQuery(value: Int!): String!
}

Note that the argument that implements GraphQLContext is not reflected in the GraphQL schema.

Spring Server

For more details on how to create the context while using graphql-kotlin-spring-server see the spring graphql context page.

Customization

The context is injected into the execution through the FunctionDataFetcher class. If you want to customize the logic on how the context is determined, that is possible to override. See more details on the Fetching Data documentation