Skip to content

Commit 1eb83a5

Browse files
committed
Await pending promises in the payload
1 parent d8d83ca commit 1eb83a5

1 file changed

Lines changed: 13 additions & 4 deletions

File tree

graphql_ws/django/consumers.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,18 @@
99

1010

1111
class JSONPromiseEncoder(json.JSONEncoder):
12+
def encode(self, *args, **kwargs):
13+
self.pending_promises = []
14+
return super(JSONPromiseEncoder, self).encode(*args, **kwargs)
15+
1216
def default(self, o):
1317
if isinstance(o, Promise):
18+
if o.is_pending:
19+
self.pending_promises.append(o)
1420
return o.value
1521
return super(JSONPromiseEncoder, self).default(o)
1622

1723

18-
json_promise_encoder = JSONPromiseEncoder()
19-
20-
2124
class GraphQLSubscriptionConsumer(AsyncJsonWebsocketConsumer):
2225
async def connect(self):
2326
self.connection_context = None
@@ -40,4 +43,10 @@ async def receive_json(self, content):
4043

4144
@classmethod
4245
async def encode_json(cls, content):
43-
return json_promise_encoder.encode(content)
46+
json_promise_encoder = JSONPromiseEncoder()
47+
e = json_promise_encoder.encode(content)
48+
while json_promise_encoder.pending_promises:
49+
# Wait for pending promises to complete, then try encoding again.
50+
await asyncio.wait(json_promise_encoder.pending_promises)
51+
e = json_promise_encoder.encode(content)
52+
return e

0 commit comments

Comments
 (0)