Skip to content

Commit c7a959d

Browse files
committed
Return dictionary and raise GraphQLException on error from GraphQL query
1 parent f58c991 commit c7a959d

File tree

3 files changed

+17
-9
lines changed

3 files changed

+17
-9
lines changed

CHANGELOG

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
== Unreleased
22

3+
- Return dictionary and raise GraphQLException on error from GraphQL query
34
- Remove requirement to provide scopes to Permission URL, as it should be omitted if defined with the TOML file.
45

56
== Version 12.7.0

shopify/resources/graphql.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,17 @@
11
import shopify
2-
from ..base import ShopifyResource
32
from six.moves import urllib
43
import json
54

65

6+
class GraphQLException(Exception):
7+
def __init__(self, response):
8+
self._response = response
9+
10+
@property
11+
def errors(self):
12+
return self._response['errors']
13+
14+
715
class GraphQL:
816
def __init__(self):
917
self.endpoint = shopify.ShopifyResource.get_site() + "/graphql.json"
@@ -16,7 +24,6 @@ def merge_headers(self, *headers):
1624
return merged_headers
1725

1826
def execute(self, query, variables=None, operation_name=None):
19-
endpoint = self.endpoint
2027
default_headers = {"Accept": "application/json", "Content-Type": "application/json"}
2128
headers = self.merge_headers(default_headers, self.headers)
2229
data = {"query": query, "variables": variables, "operationName": operation_name}
@@ -25,8 +32,9 @@ def execute(self, query, variables=None, operation_name=None):
2532

2633
try:
2734
response = urllib.request.urlopen(req)
28-
return response.read().decode("utf-8")
35+
result = json.loads(response.read().decode("utf-8"))
36+
if result.get('errors'):
37+
raise GraphQLException(result)
38+
return result
2939
except urllib.error.HTTPError as e:
30-
print((e.read()))
31-
print("")
32-
raise e
40+
raise GraphQLException(json.load(e.fp))

test/graphql_test.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import shopify
2-
import json
32
from test.test_helper import TestCase
43

54

@@ -31,7 +30,7 @@ def test_fetch_shop_with_graphql(self):
3130
}
3231
"""
3332
result = self.client.execute(query)
34-
self.assertTrue(json.loads(result)["shop"]["name"] == "Apple Computers")
33+
self.assertTrue(result["shop"]["name"] == "Apple Computers")
3534

3635
def test_specify_operation_name(self):
3736
query = """
@@ -43,4 +42,4 @@ def test_specify_operation_name(self):
4342
}
4443
"""
4544
result = self.client.execute(query, operation_name="GetShop")
46-
self.assertTrue(json.loads(result)["shop"]["name"] == "Apple Computers")
45+
self.assertTrue(result["shop"]["name"] == "Apple Computers")

0 commit comments

Comments
 (0)