|
| 1 | +--- |
| 2 | +id: spring-graphql-context |
| 3 | +title: Generating GraphQL Context |
| 4 | +--- |
| 5 | + |
| 6 | +`graphql-kotlin-spring-server` provides a simple mechanism to build [GraphQL context](../execution/contextual-data) per query execution through |
| 7 | +[GraphQLContextFactory](https://github.com/ExpediaGroup/graphql-kotlin/blob/master/graphql-kotlin-spring-server/src/main/kotlin/com/expediagroup/graphql/spring/execution/GraphQLContextFactory.kt). |
| 8 | +Once context factory bean is available in the Spring application context it will then be used in a corresponding |
| 9 | +[ContextWebFilter](https://github.com/ExpediaGroup/graphql-kotlin/blob/master/graphql-kotlin-spring-server/src/main/kotlin/com/expediagroup/graphql/spring/execution/ContextWebFilter.kt) |
| 10 | +to populate GraphQL context based on the incoming request and make it available during query execution. |
| 11 | + |
| 12 | +For example if we define our custom context as follows: |
| 13 | + |
| 14 | +```kotlin |
| 15 | +data class MyGraphQLContext(val myCustomValue: String) |
| 16 | +``` |
| 17 | + |
| 18 | +We can generate corresponding `GraphQLContextFactory` bean: |
| 19 | + |
| 20 | +```kotlin |
| 21 | +@Component |
| 22 | +class MyGraphQLContextFactory: GraphQLContextFactory<MyGraphQLContext> { |
| 23 | + override suspend fun generateContext( |
| 24 | + request: ServerHttpRequest, |
| 25 | + response: ServerHttpResponse |
| 26 | + ): MyGraphQLContext = MyGraphQLContext( |
| 27 | + myCustomValue = request.headers.getFirst("MyHeader") ?: "defaultContext" |
| 28 | + ) |
| 29 | +} |
| 30 | +``` |
| 31 | + |
| 32 | +Once your application is configured to build your custom `MyGraphQLContext`, we can then specify it as function argument by annotating it with `@GraphQLContext`. |
| 33 | +While executing the query, the corresponding GraphQL context will be read from the environment and automatically injected to the function input arguments. |
| 34 | + |
| 35 | +```kotlin |
| 36 | +@Component |
| 37 | +class ContextualQuery: Query { |
| 38 | + fun contextualQuery( |
| 39 | + value: Int, |
| 40 | + @GraphQLContext context: MyGraphQLContext |
| 41 | + ): ContextualResponse = ContextualResponse(value, context.myCustomValue) |
| 42 | +} |
| 43 | +``` |
| 44 | + |
| 45 | +The above query would produce the following GraphQL schema: |
| 46 | + |
| 47 | +```graphql |
| 48 | +schema { |
| 49 | + query: Query |
| 50 | +} |
| 51 | + |
| 52 | +type Query { |
| 53 | + contextualQuery( |
| 54 | + value: Int! |
| 55 | + ): ContextualResponse! |
| 56 | +} |
| 57 | +``` |
| 58 | + |
| 59 | +Notice that the `@GraphQLContext` annotated argument is not reflected in the generated GraphQL schema. |
0 commit comments