11from __future__ import annotations
22
3+ import json
4+ import re
35from dataclasses import dataclass
46from graphql .language import DocumentNode
57from typing import TYPE_CHECKING , Any , Optional
@@ -26,6 +28,24 @@ def process_result(result: ExecutionResult) -> GraphQLHTTPResponse:
2628 return data
2729
2830
31+ def tojson (value ):
32+ if value not in ["true" , "false" , "null" , "undefined" ]:
33+ value = json .dumps (value )
34+ # value = escape_js_value(value)
35+ return value
36+
37+
38+ def simple_renderer (template : str , ** values : str ) -> str :
39+ def get_var (match_obj : re .Match [str ]) -> str :
40+ var_name = match_obj .group (1 )
41+ if var_name is not None :
42+ return values .get (var_name , "" )
43+ return ""
44+
45+ pattern = r"{{\s*([^}]+)\s*}}"
46+ return re .sub (pattern , get_var , template )
47+
48+
2949@dataclass
3050class GraphQLRequestData :
3151 # query is optional here as it can be added by an extensions
@@ -39,11 +59,14 @@ class GraphQLRequestData:
3959
4060 def to_template_context (self ) -> dict [str , Any ]:
4161 return {
42- "query" : self .query ,
43- "variables" : self .variables ,
44- "operationName " : self .operation_name ,
62+ "query" : tojson ( self .query ) ,
63+ "variables" : tojson ( self .variables ) ,
64+ "operation_name " : tojson ( self .operation_name ) ,
4565 }
4666
67+ def to_template_string (self , template : str ) -> str :
68+ return simple_renderer (template , ** self .to_template_context ())
69+
4770
4871__all__ = [
4972 "GraphQLHTTPResponse" ,
0 commit comments