|
| 1 | + |
| 2 | +defmodule GraphQL.Execution.ASTValue do |
| 3 | + alias GraphQL.Type.NonNull |
| 4 | + alias GraphQL.Type.List |
| 5 | + alias GraphQL.Type.Input |
| 6 | + alias GraphQL.Type.NonNull |
| 7 | + alias GraphQL.Type.CompositeType |
| 8 | + |
| 9 | + def value_from_ast(value_ast, %NonNull{ofType: inner_type}, variable_values) do |
| 10 | + value_from_ast(value_ast, inner_type, variable_values) |
| 11 | + end |
| 12 | + |
| 13 | + def value_from_ast(%{value: obj=%{kind: :ObjectValue}}, type=%Input{}, variable_values) do |
| 14 | + input_fields = CompositeType.get_fields(type) |
| 15 | + field_asts = Enum.reduce(obj.fields, %{}, fn(ast, result) -> |
| 16 | + Map.put(result, ast.name.value, ast) |
| 17 | + end) |
| 18 | + Enum.reduce(Map.keys(input_fields), %{}, fn(field_name, result) -> |
| 19 | + field = Map.get(input_fields, field_name) |
| 20 | + field_ast = Map.get(field_asts, to_string(field_name)) # this feels... brittle. |
| 21 | + inner_result = value_from_ast(field_ast, field.type, variable_values) |
| 22 | + case inner_result do |
| 23 | + nil -> result |
| 24 | + _ -> Map.put(result, field_name, inner_result) |
| 25 | + end |
| 26 | + end) |
| 27 | + end |
| 28 | + |
| 29 | + def value_from_ast(%{value: %{kind: :Variable, name: %{value: value}}}, type, variable_values) do |
| 30 | + case Map.get(variable_values, value) do |
| 31 | + nil -> nil |
| 32 | + variable_value -> GraphQL.Types.parse_value(type, variable_value) |
| 33 | + end |
| 34 | + end |
| 35 | + |
| 36 | + # if it isn't a variable or object input type, that means it's invalid |
| 37 | + # and we shoud return a nil |
| 38 | + def value_from_ast(_, %Input{}, _), do: nil |
| 39 | + |
| 40 | + def value_from_ast(%{value: %{kind: :ListValue, values: values_ast}}, type, _) do |
| 41 | + GraphQL.Types.parse_value(type, Enum.map(values_ast, fn(value_ast) -> |
| 42 | + value_ast.value |
| 43 | + end)) |
| 44 | + end |
| 45 | + |
| 46 | + def value_from_ast(value_ast, %List{ofType: inner_type}, variable_values) do |
| 47 | + [value_from_ast(value_ast, inner_type, variable_values)] |
| 48 | + end |
| 49 | + |
| 50 | + def value_from_ast(nil, _, _), do: nil # remove once NonNull is actually done.. |
| 51 | + |
| 52 | + def value_from_ast(value_ast, type, variable_values) when is_atom(type) do |
| 53 | + value_from_ast(value_ast, type.type, variable_values) |
| 54 | + end |
| 55 | + |
| 56 | + def value_from_ast(value_ast, type, _) do |
| 57 | + GraphQL.Types.parse_literal(type, value_ast.value) |
| 58 | + end |
| 59 | +end |
0 commit comments