Django GraphQL depth limit validation for each query

297 Views Asked by At

I am using django graphql and have lots of queries. I have some public queries on which anyone does deep queries.

enter image description here

I want to limit the depth of each query. Found this on the documentation https://docs.graphene-python.org/en/latest/execution/queryvalidation/ but didn't find any proper way to use it.

Also, Is there any way to pass dynamic fields to graphene fields like this:

jobs = graphene.List(JobGQLType, fields=['title', 'location'])

Any help would be really appreciated.

1

There are 1 best solutions below

0
Leonard Lu On

According to this Github issue it looks like there is no way to modify the default validation rules that the graphql-python runs on all queries. Instead, you have to add your own call to the validate method somewhere in the code that runs when a query is executed.

Here is an example of adding a depth limiting validation check to the Graphene schema execute method. Maybe there's a more efficient way, but at least I can confirm that this works.

import graphene
from graphene.validation import depth_limit_validator
from graphql import ExecutionResult, GraphQLError, parse, validate

GRAPHENE_DEPTH_LIMIT = 9

class DepthLimitValidatingSchema(graphene.Schema):
    def execute(self, *args, **kwargs):
        # If we're not executing a query from a GraphQL View, don't validate the depth
        if "source" not in kwargs:
            return super().execute(*args, **kwargs)

        try:
            document = parse(kwargs["source"])
        except GraphQLError as error:
            return ExecutionResult(data=None, errors=[error])

        validation_errors = validate(
            self.graphql_schema,
            document,
            rules=(depth_limit_validator(max_depth=GRAPHENE_DEPTH_LIMIT),),
        )
        if validation_errors:
            return ExecutionResult(data=None, errors=validation_errors)

        return super().execute(*args, **kwargs)