Skip to content

Commit 5288d1b

Browse files
committed
Implement subscribe method
1 parent c46c836 commit 5288d1b

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

python_graphql_client/graphql_client.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
"""Module containing graphQL client."""
2+
import json
3+
from typing import Callable
24

35
import aiohttp
46
import requests
7+
import websockets
58

69

710
class GraphqlClient:
@@ -66,3 +69,27 @@ async def execute_async(
6669
headers=self.__request_headers(headers),
6770
) as response:
6871
return await response.json()
72+
73+
async def subscribe(
74+
self,
75+
query: str,
76+
handle: Callable,
77+
variables: dict = None,
78+
operation_name: str = None,
79+
headers: dict = None,
80+
):
81+
"""Make asynchronous request for GraphQL subscription."""
82+
request_body = self.__request_body(
83+
query=query, variables=variables, operation_name=operation_name
84+
)
85+
request_message = json.dumps(
86+
{"type": "start", "id": "1", "payload": request_body}
87+
)
88+
89+
async with websockets.connect(
90+
self.endpoint, subprotocols=["graphql-ws"]
91+
) as websocket:
92+
await websocket.send(request_message)
93+
async for response_message in websocket:
94+
response_body = json.loads(response_message)
95+
handle(response_body["payload"])

0 commit comments

Comments
 (0)