From c73a8f08e28216866e6e762e67d0a16d7068a469 Mon Sep 17 00:00:00 2001 From: Ian Gabaraev <39344857+Ian-Gabaraev@users.noreply.github.com> Date: Sun, 20 Jun 2021 21:20:18 +0300 Subject: [PATCH] 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 --- graphene/utils/decorators.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 graphene/utils/decorators.py diff --git a/graphene/utils/decorators.py b/graphene/utils/decorators.py new file mode 100644 index 00000000..a478c5f6 --- /dev/null +++ b/graphene/utils/decorators.py @@ -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