#Context
GraphQLSwift/GraphQL allow a custom data structure to be passed into all of your field resolver functions.
The context can be in any form, but it is useful for:
- Dependencies injection to each resolver function in the schema
- Providing or deriving an operation specific value
#Operation specific contextual value
As for example, your schema resolve prices of coffee for your users which could have subscribed to a membership plan with different benefits and discount for each price of a coffee.
One approach is to add this value within the arguments, but that comes with issues of security and that fact that this value has to be explicitly given.
#Context for derived values
The context value can be used to provide additional values specific to the request that are derived outside the GraphQL request.
#Using context from resolver
This context struct can be in any form and include any values that may come in useful to be derived outside of the GraphQL request. For this example, it will contain the user who are performing the query.
#Dependencies injection
Another use case for context is to perform dependency injection to all resolvers.
As an example, you have created a PubSub implementation that uses Redis, which required to be initialised on main.swift
.
#Context for dependencies
Passing down this to each one the resolver would require dependency injection, which can be done through Context.
#Using dependencies from resolver
All of the resolvers would have access to this context and can get the pubsub
property from it and use it.