|
| 1 | +from typing import Any, Callable, Dict, Iterable, List, Union, cast |
| 2 | + |
| 3 | + |
| 4 | +from ..error import GraphQLError, INVALID |
| 5 | +from ..pyutils import Path, did_you_mean, inspect, print_path_list, suggestion_list |
| 6 | +from ..type import ( |
| 7 | + GraphQLEnumType, |
| 8 | + GraphQLInputObjectType, |
| 9 | + GraphQLInputType, |
| 10 | + GraphQLList, |
| 11 | + GraphQLScalarType, |
| 12 | + is_enum_type, |
| 13 | + is_input_object_type, |
| 14 | + is_list_type, |
| 15 | + is_non_null_type, |
| 16 | + is_scalar_type, |
| 17 | + GraphQLNonNull, |
| 18 | +) |
| 19 | + |
| 20 | +__all__ = ["coerce_input_value"] |
| 21 | + |
| 22 | + |
| 23 | +OnErrorCB = Callable[[List[Union[str, int]], Any, GraphQLError], None] |
| 24 | + |
| 25 | + |
| 26 | +def default_on_error( |
| 27 | + path: List[Union[str, int]], invalid_value: Any, error: GraphQLError |
| 28 | +) -> None: |
| 29 | + error_prefix = "Invalid value " + inspect(invalid_value) |
| 30 | + if path: |
| 31 | + error_prefix += f" at 'value{print_path_list(path)}': " |
| 32 | + error.message = error_prefix + ": " + error.message |
| 33 | + raise error |
| 34 | + |
| 35 | + |
| 36 | +def coerce_input_value( |
| 37 | + input_value: Any, |
| 38 | + type_: GraphQLInputType, |
| 39 | + on_error: OnErrorCB = default_on_error, |
| 40 | + path: Path = None, |
| 41 | +) -> Any: |
| 42 | + """Coerce a Python value given a GraphQL Input Type.""" |
| 43 | + if is_non_null_type(type_): |
| 44 | + if input_value is not None and input_value is not INVALID: |
| 45 | + type_ = cast(GraphQLNonNull, type_) |
| 46 | + return coerce_input_value(input_value, type_.of_type, on_error, path) |
| 47 | + on_error( |
| 48 | + path.as_list() if path else [], |
| 49 | + input_value, |
| 50 | + GraphQLError( |
| 51 | + f"Expected non-nullable type {inspect(type_)} not to be None." |
| 52 | + ), |
| 53 | + ) |
| 54 | + return INVALID |
| 55 | + |
| 56 | + if input_value is None or input_value is INVALID: |
| 57 | + # Explicitly return the value null. |
| 58 | + return None |
| 59 | + |
| 60 | + if is_list_type(type_): |
| 61 | + type_ = cast(GraphQLList, type_) |
| 62 | + item_type = type_.of_type |
| 63 | + if isinstance(input_value, Iterable) and not isinstance(input_value, str): |
| 64 | + coerced_list: List[Any] = [] |
| 65 | + append_item = coerced_list.append |
| 66 | + for index, item_value in enumerate(input_value): |
| 67 | + append_item( |
| 68 | + coerce_input_value( |
| 69 | + item_value, item_type, on_error, Path(path, index) |
| 70 | + ) |
| 71 | + ) |
| 72 | + return coerced_list |
| 73 | + # Lists accept a non-list value as a list of one. |
| 74 | + return [coerce_input_value(input_value, item_type, on_error, path)] |
| 75 | + |
| 76 | + if is_input_object_type(type_): |
| 77 | + type_ = cast(GraphQLInputObjectType, type_) |
| 78 | + if not isinstance(input_value, dict): |
| 79 | + on_error( |
| 80 | + path.as_list() if path else [], |
| 81 | + input_value, |
| 82 | + GraphQLError(f"Expected type {type_.name} to be a dict."), |
| 83 | + ) |
| 84 | + return INVALID |
| 85 | + |
| 86 | + coerced_dict: Dict[str, Any] = {} |
| 87 | + fields = type_.fields |
| 88 | + |
| 89 | + for field_name, field in fields.items(): |
| 90 | + field_value = input_value.get(field_name, INVALID) |
| 91 | + |
| 92 | + if field_value is INVALID: |
| 93 | + if field.default_value is not INVALID: |
| 94 | + # Use out name as name if it exists (extension of GraphQL.js). |
| 95 | + coerced_dict[field.out_name or field_name] = field.default_value |
| 96 | + elif is_non_null_type(field.type): |
| 97 | + type_str = inspect(field.type) |
| 98 | + on_error( |
| 99 | + path.as_list() if path else [], |
| 100 | + input_value, |
| 101 | + GraphQLError( |
| 102 | + f"Field {field_name} of required type {type_str}" |
| 103 | + " was not provided." |
| 104 | + ), |
| 105 | + ) |
| 106 | + continue |
| 107 | + |
| 108 | + coerced_dict[field.out_name or field_name] = coerce_input_value( |
| 109 | + field_value, field.type, on_error, Path(path, field_name) |
| 110 | + ) |
| 111 | + |
| 112 | + # Ensure every provided field is defined. |
| 113 | + for field_name in input_value: |
| 114 | + if field_name not in fields: |
| 115 | + suggestions = suggestion_list(field_name, fields) |
| 116 | + on_error( |
| 117 | + path.as_list() if path else [], |
| 118 | + input_value, |
| 119 | + GraphQLError( |
| 120 | + f"Field '{field_name}' is not defined by type {type_.name}." |
| 121 | + + did_you_mean(suggestions) |
| 122 | + ), |
| 123 | + ) |
| 124 | + return type_.out_type(coerced_dict) |
| 125 | + |
| 126 | + if is_scalar_type(type_): |
| 127 | + # Scalars determine if a value is valid via `parse_value()`, which can throw to |
| 128 | + # indicate failure. If it throws, maintain a reference to the original error. |
| 129 | + type_ = cast(GraphQLScalarType, type_) |
| 130 | + try: |
| 131 | + parse_result = type_.parse_value(input_value) |
| 132 | + except (TypeError, ValueError) as error: |
| 133 | + on_error( |
| 134 | + path.as_list() if path else [], |
| 135 | + input_value, |
| 136 | + GraphQLError( |
| 137 | + f"Expected type {type_.name}. {error}", original_error=error |
| 138 | + ), |
| 139 | + ) |
| 140 | + return INVALID |
| 141 | + if parse_result is INVALID: |
| 142 | + on_error( |
| 143 | + path.as_list() if path else [], |
| 144 | + input_value, |
| 145 | + GraphQLError(f"Expected type {type_.name}."), |
| 146 | + ) |
| 147 | + return parse_result |
| 148 | + |
| 149 | + if is_enum_type(type_): |
| 150 | + type_ = cast(GraphQLEnumType, type_) |
| 151 | + values = type_.values |
| 152 | + if isinstance(input_value, str): |
| 153 | + enum_value = values.get(input_value) |
| 154 | + if enum_value: |
| 155 | + return enum_value.value |
| 156 | + suggestions = suggestion_list(str(input_value), values) |
| 157 | + on_error( |
| 158 | + path.as_list() if path else [], |
| 159 | + input_value, |
| 160 | + GraphQLError(f"Expected type {type_.name}." + did_you_mean(suggestions)), |
| 161 | + ) |
| 162 | + return INVALID |
| 163 | + |
| 164 | + # Not reachable. All possible input types have been considered. |
| 165 | + raise TypeError(f"Unexpected input type: '{inspect(type_)}'.") # pragma: no cover |
0 commit comments