mirror of
https://github.com/graphql-python/graphene.git
synced 2025-04-25 03:43:42 +03:00
47 lines
1.5 KiB
Python
47 lines
1.5 KiB
Python
from ..pyutils.compat import signature
|
|
from functools import wraps
|
|
|
|
|
|
def resolver_from_annotations(func):
|
|
from ..types import Context, ResolveInfo
|
|
|
|
_is_wrapped_from_annotations = is_wrapped_from_annotations(func)
|
|
assert not _is_wrapped_from_annotations, "The function {func_name} is already wrapped.".format(
|
|
func_name=func.func_name
|
|
)
|
|
|
|
func_signature = signature(func)
|
|
|
|
_context_var = None
|
|
_info_var = None
|
|
for key, parameter in func_signature.parameters.items():
|
|
param_type = parameter.annotation
|
|
if param_type is Context:
|
|
_context_var = key
|
|
elif param_type is ResolveInfo:
|
|
_info_var = key
|
|
continue
|
|
|
|
# We generate different functions as it will be faster
|
|
# than calculating the args on the fly when executing
|
|
# the function resolver.
|
|
if _context_var and _info_var:
|
|
def inner(root, args, context, info):
|
|
return func(root, **dict(args, **{_info_var: info, _context_var: context}))
|
|
elif _context_var:
|
|
def inner(root, args, context, info):
|
|
return func(root, **dict(args, **{_context_var: context}))
|
|
elif _info_var:
|
|
def inner(root, args, context, info):
|
|
return func(root, **dict(args, **{_info_var: info}))
|
|
else:
|
|
def inner(root, args, context, info):
|
|
return func(root, **args)
|
|
|
|
inner._is_wrapped_from_annotations = True
|
|
return wraps(func)(inner)
|
|
|
|
|
|
def is_wrapped_from_annotations(func):
|
|
return getattr(func, '_is_wrapped_from_annotations', False)
|