Skip to content

Commit d6b4458

Browse files
committed
feat: add support for jinja renderer
1 parent 1972b27 commit d6b4458

File tree

3 files changed

+39
-26
lines changed

3 files changed

+39
-26
lines changed

graphql_server/render_graphiql.py

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
"""Based on (express-graphql)[https://github.com/graphql/express-graphql/blob/main/src/renderGraphiQL.ts] and
2-
(subscriptions-transport-ws)[https://github.com/apollographql/subscriptions-transport-ws]"""
2+
(graphql-ws)[https://github.com/enisdenjo/graphql-ws]"""
33
import json
44
import re
55
from typing import Any, Dict, Optional, Tuple
@@ -216,24 +216,12 @@ class GraphiQLOptions(TypedDict):
216216
should_persist_headers: Optional[bool]
217217

218218

219-
def escape_js_value(value: Any) -> Any:
220-
quotation = False
221-
if value.startswith('"') and value.endswith('"'):
222-
quotation = True
223-
value = value[1 : len(value) - 1]
224-
225-
value = value.replace("\\\\n", "\\\\\\n").replace("\\n", "\\\\n")
226-
if quotation:
227-
value = '"' + value.replace('\\\\"', '"').replace('"', '\\"') + '"'
228-
229-
return value
230-
231-
232219
def process_var(template: str, name: str, value: Any, jsonify=False) -> str:
233-
pattern = r"{{\s*" + name + r"(\s*|[^}]+)*\s*}}"
220+
pattern = r"{{\s*" + name.replace("\\", r"\\") + r"(\s*|[^}]+)*\s*}}"
234221
if jsonify and value not in ["null", "undefined"]:
235222
value = json.dumps(value)
236-
value = escape_js_value(value)
223+
224+
value = value.replace("\\", r"\\")
237225

238226
return re.sub(pattern, value, template)
239227

@@ -296,6 +284,9 @@ def _render_graphiql(
296284
or "false",
297285
}
298286

287+
if template_vars["result"] in ("null"):
288+
template_vars["result"] = None
289+
299290
return graphiql_template, template_vars
300291

301292

@@ -305,7 +296,7 @@ async def render_graphiql_async(
305296
options: Optional[GraphiQLOptions] = None,
306297
) -> str:
307298
graphiql_template, template_vars = _render_graphiql(data, config, options)
308-
jinja_env: Optional[Environment] = config.get("jinja_env")
299+
jinja_env = config.get("jinja_env")
309300

310301
if jinja_env:
311302
template = jinja_env.from_string(graphiql_template)
@@ -324,6 +315,11 @@ def render_graphiql_sync(
324315
options: Optional[GraphiQLOptions] = None,
325316
) -> str:
326317
graphiql_template, template_vars = _render_graphiql(data, config, options)
318+
jinja_env = config.get("jinja_env")
327319

328-
source = simple_renderer(graphiql_template, **template_vars)
320+
if jinja_env:
321+
template = jinja_env.from_string(graphiql_template)
322+
source = template.render(**template_vars)
323+
else:
324+
source = simple_renderer(graphiql_template, **template_vars)
329325
return source

tests/sanic/app.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,14 @@
88
from .schema import Schema
99

1010

11-
def create_app(path="/graphql", **kwargs):
11+
def create_app(path="/graphql", schema=Schema, **kwargs):
1212
random_valid_app_name = f"App{uuid.uuid4().hex}"
1313
app = Sanic(random_valid_app_name)
1414

15-
schema = kwargs.pop("schema", None) or Schema
1615
app.add_route(GraphQLView.as_view(schema=schema, **kwargs), path)
1716

1817
return app
1918

2019

2120
def url_string(uri="/graphql", **url_params):
22-
string = "/graphql"
23-
24-
if url_params:
25-
string += "?" + urlencode(url_params)
26-
27-
return string
21+
return f"{uri}?{urlencode(url_params)}" if url_params else uri

tests/test_query.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,11 @@
1515
load_json_body,
1616
run_http_query,
1717
)
18+
from graphql_server.render_graphiql import (
19+
GraphiQLConfig,
20+
GraphiQLData,
21+
render_graphiql_sync,
22+
)
1823

1924
from .schema import invalid_schema, schema
2025
from .utils import as_dicts
@@ -653,3 +658,21 @@ def test_batch_allows_post_with_operation_name():
653658
results, params = run_http_query(schema, "post", data, batch_enabled=True)
654659

655660
assert results == [({"test": "Hello World", "shared": "Hello Everyone"}, None)]
661+
662+
663+
def test_graphiql_render_umlaut():
664+
results, params = run_http_query(
665+
schema,
666+
"get",
667+
data=dict(query="query helloWho($who: String){ test(who: $who) }"),
668+
query_data=dict(variables='{"who": "Björn"}'),
669+
catch=True,
670+
)
671+
result, status_code = encode_execution_results(results)
672+
673+
assert status_code == 200
674+
675+
graphiql_data = GraphiQLData(result=result, query=params[0].query)
676+
source = render_graphiql_sync(data=graphiql_data, config=GraphiQLConfig())
677+
678+
assert "Hello Bj\\\\u00f6rn" in source

0 commit comments

Comments
 (0)