question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Having custom validation over scalars

See original GitHub issue

I need to pass some validation check when defining Arguments for Mutation. I know I can check it inside the mutate function but I need this check before that (similar to what we have in marshmallow.validate module: Range and Length).

I just want to know if there is any future plan to implement it inside the graphene or not.

Issue Analytics

  • State:open
  • Created 4 years ago
  • Comments:17 (2 by maintainers)

github_iconTop GitHub Comments

7reactions
adamsangheracommented, Oct 7, 2021

Putting up this interface for consideration, which would mirror interfaces from similar libraries with validation hooks.

def is_valid_email(value: str) -> bool:
    """Validate an email.

    :raises: ValidationError, if email is invalid.
    """
    # whatever
    return True

class Foo(graphene.Mutation):
    class Arguments:
        email_address = graphene.String(validators=[is_valid_email])

I’m not very familiar with graphene’s internals, but I think you could add a function, Field.validate, and add validators: [Callable -> bool] to __init__.

def validate(self, value):
    for validator in self.validators:
        validator(value)
    return value

which would then be called, after the value is resolved (this part I’m less familiar with).

This would be a fairly large extension to the surface area of Field which is, at present, quite narrow.

However, there are many lines of code spilled over more-magical implementations of validate. IMO, graphene deserves to have validation as a first-party feature, and for it to be a “declarative” implementation, so you can understand the input space of a variable in one closure.

If a maintainer validates (zing) that this would be a desirable interface, I’d be happy to take a stab at it.

2reactions
vancouverwillcommented, Jun 9, 2020

Sure, you can pass kwargs but where exactly would the validation logic run and be called? parse_value, serialize? Also there’s no access to the supertype so what if I wanted to show a hierarchy/path to the wrong value (e.g. items[0].email is invalid)?

@chpmrc I got the validation we needed working by using a custom Scalar and adding the validation on parse_value() as that does get called by the Graphene library before input is passed to either query or mutations. Adding an example here as the docs are super sparse and might of help to you or someone else in the future

class Email(String):

    @staticmethod
    def parse_value(value: Text) -> Text:
        if is_valid_email(value):
            return value
        raise GraphQLError(
                f"Invalid Graph ID {value}, should be hexadecimal format 0x1f1f"
            )

def is_valid_email(email):
    # do some regex or other validation
Read more comments on GitHub >

github_iconTop Results From Across the Web

GraphQL custom Scalar validation - node.js - Stack Overflow
So, when your query is validated by the local schema, it has no way to know whether custom scalar values are valid because...
Read more >
Custom scalars - Apollo GraphQL Docs
You can now use MyCustomScalar in your schema anywhere you can use a default scalar (e.g., as the type of an object field,...
Read more >
Centralized Validation with GraphQL Scalar Types
However, you now have the opportunity to refactor your validation to one central point, using a schema-driven approach: custom scalar types.
Read more >
Custom Scalars vs. Resolver Validation : r/graphql - Reddit
I'm trying to determine whether to lean on extensive custom ... Scalars are not as easy because they have a more demanding specification....
Read more >
Argument and Input validation - TypeGraphQL
The standard way to ensure that inputs and arguments are correct, such as an email field that really contains a proper e-mail address,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found