This repository has been archived by the owner on Jun 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhuman_readable.py
62 lines (43 loc) · 1.91 KB
/
human_readable.py
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
""" Make GraphQL errors more human-readable.
This module improves the way Int, Float and Bool objects report errors.
The new error message is human-readable and can be reported to the end-user.
Before:
> 'message': "Int cannot represent non-integer value: 'INVALID'",
After:
> 'message': "Not a valid number", # Improved, human-readable
"""
from typing import Any
import graphql.type.scalars
import graphql.type.definition
from apiens.translate import _
def install_types_to_schema(schema: graphql.GraphQLSchema):
""" Augment built-in types with user-friendly error messages
This function will replace parsers for: Int, Float, Bool, etc
with an alternative version that returns better, user-friendly, and structured, error messages.
"""
for type_name, parse_value_func in SCALAR_PARSE_VALUE_MAP.items():
type: graphql.GraphQLScalarType = schema.type_map.get(type_name) # type: ignore[assignment]
if type is not None:
type.parse_value = parse_value_func # type: ignore[assignment]
def coerce_int(input_value: Any) -> int:
try:
return graphql.type.scalars.coerce_int(input_value)
# return pydantic.validators.int_validator(input_value)
except graphql.GraphQLError as e:
raise graphql.GraphQLError(_('Not a valid number')) from e
def coerce_float(input_value: Any) -> float:
try:
return graphql.type.scalars.coerce_float(input_value)
# return pydantic.validators.float_validator(input_value)
except graphql.GraphQLError as e:
raise graphql.GraphQLError(_('Not a valid number')) from e
def coerce_bool(input_value: Any) -> bool:
try:
return graphql.type.scalars.coerce_boolean(input_value)
except graphql.GraphQLError as e:
raise graphql.GraphQLError(_('Not a valid yes/no value')) from e
SCALAR_PARSE_VALUE_MAP = {
'Int': coerce_int,
'Float': coerce_float,
'Boolean': coerce_bool,
}