It would be very useful to have possibility to define field level validators especially for those fields which do not have resolvers. My proposal is to add validators parameter to field to strawberry.field
and validator decorator. This idea came to my mind when I was designing API for strawberry-graphql-django
package (strawberry-graphql/strawberry-django#10). Soon we realized that this could be core feature of strawberry
library.
I implemented prototype code and made draft pull request #809.
Validators could be used for following purposes
I'd propose following syntax for validators
def permission_validator(value, info):
if not info.context.request.user.has_permission():
raise Exception('Permission denied')
return value
@strawberry.type
class User:
name: str = strawberry.field(validators=[permission_validator])
I'd also propose decorator syntax, which is quite similar with existing field resolver syntax. Strawberry field would provide validator decorator which could be then used to tie the field together with validator function.
@strawberry.input
class UserInput:
name: str = strawberry.field()
@name.validator
def name_validator(value, info):
if 'bad' in value:
raise ValueError('name contains bad word')
return value.title()
def permission_validator(value, info):
if not info.context.request.user.has_permission():
raise Exception('Permission denied')
return value
@strawberry.type
class User:
# this does not work
@strawberry.validator(permission_validator)
name: str = strawberry.field()
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too