-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy path__init__.py
More file actions
89 lines (69 loc) · 2.62 KB
/
__init__.py
File metadata and controls
89 lines (69 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
from __future__ import annotations
import json
import re
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Optional
from typing_extensions import Literal, TypedDict
from graphql.language import DocumentNode
if TYPE_CHECKING:
from graphql import ExecutionResult
class GraphQLHTTPResponse(TypedDict, total=False):
data: Optional[dict[str, object]]
errors: Optional[list[object]]
extensions: Optional[dict[str, object]]
def process_result(
result: ExecutionResult, strict: bool = False
) -> GraphQLHTTPResponse:
if strict and not result.data:
data: GraphQLHTTPResponse = {}
else:
data: GraphQLHTTPResponse = {"data": result.data}
if result.errors:
data["errors"] = [err.formatted for err in result.errors]
if result.extensions:
data["extensions"] = result.extensions
return data
def tojson(value):
if value not in ["true", "false", "null", "undefined"]:
value = json.dumps(value)
# Escape characters that are significant to the HTML parser when
# embedded inside <script> tags. Using JS Unicode escapes (\u003c)
# rather than HTML entities (<) so JavaScript correctly decodes
# them at runtime while the HTML parser never sees raw < or >.
value = value.replace("<", "\\u003c").replace(">", "\\u003e")
return value
def simple_renderer(template: str, **values: str) -> str:
def get_var(match_obj: re.Match[str]) -> str:
var_name = match_obj.group(1)
if var_name is not None:
return values.get(var_name) or tojson("")
return ""
pattern = r"{{\s*([^}]+)\s*}}"
return re.sub(pattern, get_var, template)
@dataclass
class GraphQLRequestData:
# query is optional here as it can be added by an extensions
# (for example an extension for persisted queries)
query: Optional[str]
document: Optional[DocumentNode]
variables: Optional[dict[str, Any]]
operation_name: Optional[str]
extensions: Optional[dict[str, Any]]
protocol: Literal[
"http", "http-strict", "multipart-subscription", "subscription"
] = "http"
def to_template_context(self) -> dict[str, Any]:
return {
"query": tojson(self.query),
"variables": tojson(
tojson(self.variables) if self.variables is not None else ""
),
"operation_name": tojson(self.operation_name),
}
def to_template_string(self, template: str) -> str:
return simple_renderer(template, **self.to_template_context())
__all__ = [
"GraphQLHTTPResponse",
"GraphQLRequestData",
"process_result",
]