From c7a959d9f91469d607aef6652fea963ca05da38c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Krier?= Date: Wed, 7 May 2025 14:44:37 +0200 Subject: [PATCH] Return dictionary and raise GraphQLException on error from GraphQL query --- CHANGELOG | 1 + shopify/resources/graphql.py | 20 ++++++++++++++------ test/graphql_test.py | 5 ++--- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index e9910c2e..bcbb79cc 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,6 @@ == Unreleased +- Return dictionary and raise GraphQLException on error from GraphQL query - Remove requirement to provide scopes to Permission URL, as it should be omitted if defined with the TOML file. == Version 12.7.0 diff --git a/shopify/resources/graphql.py b/shopify/resources/graphql.py index 33525ef1..ef9bb43f 100644 --- a/shopify/resources/graphql.py +++ b/shopify/resources/graphql.py @@ -1,9 +1,17 @@ import shopify -from ..base import ShopifyResource from six.moves import urllib import json +class GraphQLException(Exception): + def __init__(self, response): + self._response = response + + @property + def errors(self): + return self._response['errors'] + + class GraphQL: def __init__(self): self.endpoint = shopify.ShopifyResource.get_site() + "/graphql.json" @@ -16,7 +24,6 @@ def merge_headers(self, *headers): return merged_headers def execute(self, query, variables=None, operation_name=None): - endpoint = self.endpoint default_headers = {"Accept": "application/json", "Content-Type": "application/json"} headers = self.merge_headers(default_headers, self.headers) data = {"query": query, "variables": variables, "operationName": operation_name} @@ -25,8 +32,9 @@ def execute(self, query, variables=None, operation_name=None): try: response = urllib.request.urlopen(req) - return response.read().decode("utf-8") + result = json.loads(response.read().decode("utf-8")) + if result.get('errors'): + raise GraphQLException(result) + return result except urllib.error.HTTPError as e: - print((e.read())) - print("") - raise e + raise GraphQLException(json.load(e.fp)) diff --git a/test/graphql_test.py b/test/graphql_test.py index dc32b935..ec2b7235 100644 --- a/test/graphql_test.py +++ b/test/graphql_test.py @@ -1,5 +1,4 @@ import shopify -import json from test.test_helper import TestCase @@ -31,7 +30,7 @@ def test_fetch_shop_with_graphql(self): } """ result = self.client.execute(query) - self.assertTrue(json.loads(result)["shop"]["name"] == "Apple Computers") + self.assertTrue(result["shop"]["name"] == "Apple Computers") def test_specify_operation_name(self): query = """ @@ -43,4 +42,4 @@ def test_specify_operation_name(self): } """ result = self.client.execute(query, operation_name="GetShop") - self.assertTrue(json.loads(result)["shop"]["name"] == "Apple Computers") + self.assertTrue(result["shop"]["name"] == "Apple Computers")