|
1 | 1 | from django.db import connections
|
2 | 2 |
|
3 |
| -from promise import Promise |
4 |
| - |
| 3 | +from asgiref.sync import sync_to_async |
| 4 | +import inspect |
5 | 5 | from .sql.tracking import unwrap_cursor, wrap_cursor
|
6 | 6 | from .exception.formating import wrap_exception
|
7 | 7 | from .types import DjangoDebug
|
@@ -69,3 +69,26 @@ def resolve(self, next, root, info, **args):
|
69 | 69 | return context.django_debug.on_resolve_error(e)
|
70 | 70 | context.django_debug.add_result(result)
|
71 | 71 | return result
|
| 72 | + |
| 73 | + |
| 74 | +class DjangoSyncRequiredMiddleware: |
| 75 | + def resolve(self, next, root, info, **args): |
| 76 | + parent_type = info.parent_type |
| 77 | + |
| 78 | + ## Anytime the parent is a DjangoObject type |
| 79 | + # and we're resolving a sync field, we need to wrap it in a sync_to_async |
| 80 | + if hasattr(parent_type, "graphene_type") and hasattr( |
| 81 | + parent_type.graphene_type._meta, "model" |
| 82 | + ): |
| 83 | + if not inspect.iscoroutinefunction(next): |
| 84 | + return sync_to_async(next)(root, info, **args) |
| 85 | + |
| 86 | + ## In addition, if we're resolving to a DjangoObject type |
| 87 | + # we likely need to wrap it in a sync_to_async as well |
| 88 | + if hasattr(info.return_type, "graphene_type") and hasattr( |
| 89 | + info.return_type.graphene_type._meta, "model" |
| 90 | + ): |
| 91 | + if not info.is_awaitable(next): |
| 92 | + return sync_to_async(next)(root, info, **args) |
| 93 | + |
| 94 | + return next(root, info, **args) |
0 commit comments