mirror of
https://github.com/graphql-python/graphene.git
synced 2025-07-22 13:59:51 +03:00
Create decorators.py
Adds a decorator for handling situations when a query expects different arguments, but can only work with one. For instance: A query named "get_user" can retrieve a user email id or username, but not both. In this case, we define the query as follows: from graphene.utils.decorators import either @either(["username", "email"]) def resolve_user_by_attr(root, info, username=None, email=None): ... If both arguments were passed, the query will raise TooManyArgs. If no expected argument was passed, the query will raise TooFewArgs
This commit is contained in:
parent
355601bd5c
commit
c73a8f08e2
23
graphene/utils/decorators.py
Normal file
23
graphene/utils/decorators.py
Normal file
|
@ -0,0 +1,23 @@
|
|||
class TooManyArgs(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class TooFewArgs(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def either(expected):
|
||||
def inner(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
|
||||
arg_list = [kwargs.get(arg, None) is not None for arg in expected]
|
||||
|
||||
if not any(arg_list):
|
||||
raise TooFewArgs("Too few arguments, must be either of: " + ",".join(expected))
|
||||
|
||||
if all(arg_list):
|
||||
raise TooManyArgs("Too many arguments, must be either of: " + ",".join(expected))
|
||||
|
||||
return func(*args, **kwargs)
|
||||
return wrapper
|
||||
return inner
|
Loading…
Reference in New Issue
Block a user