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:
Ian Gabaraev 2021-06-20 21:20:18 +03:00 committed by Erik Wrede
parent 355601bd5c
commit c73a8f08e2

View 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