-
Notifications
You must be signed in to change notification settings - Fork 818
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add some validation to input arguments
- Loading branch information
Showing
2 changed files
with
159 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,57 @@ | ||
from typing import List | ||
|
||
from graphene.types.field import Field | ||
from graphene.types.inputobjecttype import InputObjectType | ||
from graphene.types.scalars import Scalar | ||
from graphene.utils.str_converters import to_camel_case | ||
|
||
|
||
class MutationInvalidArgumentsError(Exception): | ||
def __init__(self, mutation_name: str, invalid_arguments: List[str]): | ||
invalid_arguments = sorted(invalid_arguments) | ||
|
||
if len(invalid_arguments) == 1: | ||
message = ( | ||
f"Argument `{invalid_arguments[0]}` is not a valid type " | ||
f"in mutation `{mutation_name}`. " | ||
) | ||
else: | ||
head = ", ".join(invalid_arguments[:-1]) | ||
message = ( | ||
f"Arguments `{head}` and `{invalid_arguments[-1]}` are not valid types " | ||
f"in mutation `{mutation_name}`. " | ||
) | ||
|
||
message += "Arguments to a mutation need to be either a Scalar type or an InputObjectType." | ||
|
||
super().__init__(message) | ||
|
||
|
||
def mutation(return_type, arguments=None, **kwargs): | ||
# TODO: validate input arguments | ||
if arguments is None: | ||
arguments = {} | ||
|
||
def decorate(resolver_function): | ||
name = kwargs.pop("name", None) or resolver_function.__name__ | ||
description = kwargs.pop("description", None) or resolver_function.__doc__ | ||
|
||
invalid_arguments = [] | ||
for argument_name, argument in arguments.items(): | ||
if not ( | ||
isinstance(argument, Scalar) or isinstance(argument, InputObjectType) | ||
): | ||
invalid_arguments.append(argument_name) | ||
|
||
if len(invalid_arguments) > 0: | ||
raise MutationInvalidArgumentsError(name, invalid_arguments) | ||
|
||
return Field( | ||
return_type, | ||
args=arguments, | ||
name=to_camel_case(name), | ||
resolver=resolver_function, | ||
description=description, | ||
**kwargs | ||
**kwargs, | ||
) | ||
|
||
return decorate |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters