Skip to content

Commit

Permalink
Rejig concept to use middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
jaw9c committed May 9, 2023
1 parent 58b92e6 commit 791209f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 32 deletions.
32 changes: 2 additions & 30 deletions graphene_django/converter.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from collections import OrderedDict
from functools import singledispatch, wraps
from asyncio import get_running_loop
from asgiref.sync import sync_to_async

from django.db import models
from django.utils.encoding import force_str
Expand Down Expand Up @@ -267,20 +265,7 @@ def dynamic_type():
if not _type:
return

class CustomField(Field):
def wrap_resolve(self, parent_resolver):
resolver = super().wrap_resolve(parent_resolver)

try:
get_running_loop()
except RuntimeError:
pass
else:
resolver = sync_to_async(resolver)

return resolver

return CustomField(_type, required=not field.null)
return Field(_type, required=not field.null)

return Dynamic(dynamic_type)

Expand Down Expand Up @@ -335,20 +320,7 @@ def dynamic_type():
if not _type:
return

class CustomField(Field):
def wrap_resolve(self, parent_resolver):
resolver = super().wrap_resolve(parent_resolver)

try:
get_running_loop()
except RuntimeError:
pass
else:
resolver = sync_to_async(resolver)

return resolver

return CustomField(
return Field(
_type,
description=get_django_field_description(field),
required=not field.null,
Expand Down
27 changes: 25 additions & 2 deletions graphene_django/debug/middleware.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from django.db import connections

from promise import Promise

from asgiref.sync import sync_to_async
import inspect
from .sql.tracking import unwrap_cursor, wrap_cursor
from .exception.formating import wrap_exception
from .types import DjangoDebug
Expand Down Expand Up @@ -69,3 +69,26 @@ def resolve(self, next, root, info, **args):
return context.django_debug.on_resolve_error(e)
context.django_debug.add_result(result)
return result


class DjangoSyncRequiredMiddleware:
def resolve(self, next, root, info, **args):
parent_type = info.parent_type

## Anytime the parent is a DjangoObject type
# and we're resolving a sync field, we need to wrap it in a sync_to_async
if hasattr(parent_type, "graphene_type") and hasattr(
parent_type.graphene_type._meta, "model"
):
if not inspect.iscoroutinefunction(next):
return sync_to_async(next)(root, info, **args)

## In addition, if we're resolving to a DjangoObject type
# we likely need to wrap it in a sync_to_async as well
if hasattr(info.return_type, "graphene_type") and hasattr(
info.return_type.graphene_type._meta, "model"
):
if not info.is_awaitable(next):
return sync_to_async(next)(root, info, **args)

return next(root, info, **args)

0 comments on commit 791209f

Please sign in to comment.