strawberry-graphql / strawberry-django

Strawberry GraphQL Django extension
MIT License
393 stars 115 forks source link

feature: provide path to nested field if ValidationError is raised #404

Open tokr-bit opened 8 months ago

tokr-bit commented 8 months ago

Summary

This is based on the Feature Request in https://github.com/strawberry-graphql/strawberry-graphql-django/issues/398.

If a nested object is updated with a value that raises ValidationError, the field name is shown in the OperationInfo is shown that lead tot his error. It might be advantageous to see the actual nested path.

Feature Request Type

Description

Assume we have a parent with a nested field:

class Parent(models.Model);
   foo_field = models.CharField()

class Child(models.Model):
   url = models.URLField(validators=[validators.validate_url])
   parent_field = models.ForeignKey(to=Parent, related_name="children")

with some types and mutations

@strawberry.type(Child, exclude=["parent_field"])
class Child:
    id: auto
    url: auto

@strawberry.input(Child)
class ChildInput(Child):
   pass

@strawberry.type(Parent)
class Parent:
   id: auto
   foo_field: auto
   children: List[Child]

@strawberry.input(Parent)
class ParentInput(Parent):
   pass

@strawberry.type
class Mutation:
    parent: Parent = mutations.create(types.ParentInput)

Assume the following mutation:

        createParent(data: {
            fooField: "foo"
            children: [
                {
                    url: "unsupportedUrl"
                }
            ]
        }) {
            ... on OperationInfo {
                messages {
                    code
                    kind
                    field
                }
            }
        }
    }

Desired behavior: field should be Parent.children.url. Actual behavior: field is url

Solution

Currently, we catch ValidationErrors that are raised by django in _get_validation_errors (https://github.com/strawberry-graphql/strawberry-graphql-django/blob/main/strawberry_django/mutations/fields.py#L59). We would need some kind of root parameter that allows us to backtrace this field.

Do you have any suggestions on that?

Upvote & Fund

Fund with Polar