Graphene Django – How to add extensions to the response object

Graphene Django – How to add extensions to the response object


0

It’s fairly common practice in GraphQL to return custom data on an extensions field (Facebook use this for image prefetch URLs for example).

I am trying to do this in Graphene, and have made an attempt to do this in execute_graphql_request.

class CustomGraphQLView(GraphQLView):

    def execute_graphql_request(self, request, *args, **kwargs):
        result = super().execute_graphql_request(request, *args, **kwargs)

        result.extensions['a'] = 'b' 
        result.data['viewer']['test'] = 'blah' # This "works", in that it attaches 'blah' to data

        print(result.extensions) # This correctly prints {'a': 'b'}
        print(result) # This returns the whole result object WITHOUT extensions. The 'test': 'blah' data is added to the data itself though.
     
        return result

As you can see from the print output in the snippet above, this doesn’t seem to correctly attach the desired extensions object to the result. I’ve tried a number of different ways of doing this.

Any idea how I can get this to work? Is there a better way?

1 Answer
1


0

You can override the format_error method in the GraphQLView to add the extensions.

class CustomGraphQLView(GraphQLView):
    @staticmethod
    def format_error(error):
        formatted = error.formatted
        if hasattr(error, "original_error") and isinstance(
            error.original_error, CustomGraphQLError
        ):
            code = error.original_error.code
            formatted["extensions"] = {"code": code}
        return formatted
  • Check for the original exception (not the graphql one)
  • If it contains a code (in my case), add it to the extensions dict

Another way to do this would be via the GraphQLError. The constructor accepts an extension dict which will be formatted and given in the response without customisation.

raise GraphQLError(message, extension={})



Leave a Reply

Your email address will not be published. Required fields are marked *