首页 > 解决方案 > 如何限制草莓-graphql(Django实现)中的查询深度?

问题描述

我的草莓-graphql 模式解析器实现中有一个嵌套结构。关于如何限制草莓-graphql(Django 实现)中的查询深度的任何建议?

标签: djangographqldepth

解决方案


这将很快成为草莓中的一个功能:https ://github.com/strawberry-graphql/strawberry/pull/1021

您将能够定义一个可以传递给execute命令的验证器:

import strawberry
from strawberry.schema import default_validation_rules
from strawberry.tools import depth_limit_validator
# Add the depth limit validator to the list of default validation rules
validation_rules = (
  default_validation_rules + [depth_limit_validator(3)]
)
# assuming you already have a schema
result = schema.execute_sync(
    """
    query MyQuery {
      user {
        pets {
          owner {
            pets {
              name
            }
          }
        }
      }
    }
    """,
    validation_rules=validation_rules,
  )
)
assert len(result.errors) == 1
assert result.errors[0].message == "'MyQuery' exceeds maximum operation depth of 3"

推荐阅读