Skip to content

Commit b5a9728

Browse files
committed
Implement automatic persisted query for getLocation
1 parent 1634426 commit b5a9728

1 file changed

Lines changed: 43 additions & 11 deletions

File tree

pyhilo/graphql.py

Lines changed: 43 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import asyncio
2+
import hashlib
23
import logging
34
import ssl
45
from typing import Any, Dict, List, Optional
56

7+
import aiohttp
68
from gql import Client, gql
79
from gql.transport.aiohttp import AIOHTTPTransport
810
from gql.transport.websockets import WebsocketsTransport
@@ -533,18 +535,48 @@ async def async_init(self) -> None:
533535
async def call_get_location_query(self, location_hilo_id: str) -> None:
534536
"""This functions calls the digital-twin and requests location id"""
535537
access_token = await self._get_access_token()
536-
transport = AIOHTTPTransport(
537-
url=f"https://{PLATFORM_HOST}/api/digital-twin/v3/graphql",
538-
headers={"Authorization": f"Bearer {access_token}"},
539-
)
540-
client = Client(transport=transport, fetch_schema_from_transport=True)
541-
query = gql(self.QUERY_GET_LOCATION)
538+
url = f"https://{PLATFORM_HOST}/api/digital-twin/v3/graphql"
539+
headers = {"Authorization": f"Bearer {access_token}"}
542540

543-
async with client as session:
544-
result = await session.execute(
545-
query, variable_values={"locationHiloId": location_hilo_id}
546-
)
547-
self._handle_query_result(result)
541+
query = self.QUERY_GET_LOCATION
542+
query_hash = hashlib.sha256(query.encode("utf-8")).hexdigest()
543+
544+
payload = {
545+
"extensions": {
546+
"persistedQuery": {
547+
"version": 1,
548+
"sha256Hash": query_hash,
549+
}
550+
},
551+
"variables": {"locationHiloId": location_hilo_id},
552+
}
553+
554+
async with aiohttp.ClientSession(headers=headers) as session:
555+
async with session.post(url, json=payload) as response:
556+
try:
557+
response_json = await response.json()
558+
except Exception as e:
559+
LOG.error("Error parsing response: %s", e)
560+
return
561+
562+
if "errors" in response_json:
563+
for error in response_json["errors"]:
564+
if error.get("message") == "PersistedQueryNotFound":
565+
payload["query"] = query
566+
async with session.post(url, json=payload) as response:
567+
try:
568+
response_json = await response.json()
569+
except Exception as e:
570+
LOG.error("Error parsing response on retry: %s", e)
571+
return
572+
break
573+
574+
if "errors" in response_json:
575+
LOG.error("GraphQL errors: %s", response_json["errors"])
576+
return
577+
578+
if "data" in response_json:
579+
self._handle_query_result(response_json["data"])
548580

549581
async def subscribe_to_device_updated(
550582
self, location_hilo_id: str, callback: callable = None

0 commit comments

Comments
 (0)