Skip to content

Commit

Permalink
Prettify request response when GraphiQL. Fixed #6
Browse files Browse the repository at this point in the history
  • Loading branch information
syrusakbary committed Dec 14, 2016
1 parent d08e093 commit e271d22
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
7 changes: 4 additions & 3 deletions flask_graphql/graphqlview.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,14 +133,15 @@ def get_response(self, request, data, show_graphiql=False):
'status': status_code,
}

result = self.json_encode(request, response)
result = self.json_encode(request, response, show_graphiql)
else:
result = None

return result, status_code

def json_encode(self, request, d):
if not self.pretty and not request.args.get('pretty'):
def json_encode(self, request, d, show_graphiql=False):
pretty = self.pretty or show_graphiql or request.args.get('pretty')
if not pretty:
return json.dumps(d, separators=(',', ':'))

return json.dumps(d, sort_keys=True,
Expand Down
14 changes: 14 additions & 0 deletions tests/test_graphiqlview.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,17 @@ def app():
def test_graphiql_is_enabled(client):
response = client.get(url_for('graphql'), headers={'Accept': 'text/html'})
assert response.status_code == 200


def test_graphiql_renders_pretty(client):
response = client.get(url_for('graphql', query='{test}'), headers={'Accept': 'text/html'})
assert response.status_code == 200
pretty_response = (
'{\n'
' "data": {\n'
' "test": "Hello World"\n'
' }\n'
'}'
).replace("\"","\\\"").replace("\n","\\n")

assert pretty_response in response.data
9 changes: 9 additions & 0 deletions tests/test_graphqlview.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,15 @@ def test_supports_pretty_printing(client):
)


@pytest.mark.parametrize('app', [create_app(pretty=False)])
def test_not_pretty_by_default(client):
response = client.get(url_string(query='{test}'))

assert response.data.decode() == (
'{"data":{"test":"Hello World"}}'
)


def test_supports_pretty_printing_by_request(client):
response = client.get(url_string(query='{test}', pretty='1'))

Expand Down

0 comments on commit e271d22

Please sign in to comment.