Modify the context in Ariadne before the resolvers

1.2k views Asked by At

How to modify the content of the context before it is passed to the resolver functions?

1

There are 1 answers

0
Teddy Markov On BEST ANSWER

Checkout the documentation for the special Ariadne type ContextValue.

The GraphQL class accepts a keyword argument context_value. It can be of any type and will be set as context.

If a callable is passed, then it will be called with the request as an argument.

So:

  1. Create a function to build the desired context

    def get_context_value(request):
        return {'request': request, 'test': "TEST"}
    
  2. Pass the function at GraphQL initialization:

    app = GraphQL(
        schema,
        context_value=get_context_value,
        debug=True,
    )
    

Context value inside resolvers:

{'request': <starlette.requests.Request object at 0x7fc363dbf370>, 'test': 'TEST'}