Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ordered result example #1

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions boxfile.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
run.config:
engine: elixir

engine.config:
runtime: elixir-1.5

engine.config:
erlang_runtime: erlang-20.1

dev_packages:
- inotify-tools

data.db:
image: nanobox/postgresql:9.6
8 changes: 4 additions & 4 deletions config/dev.exs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use Mix.Config
# watchers to your application. For example, we use it
# with brunch.io to recompile .js and .css sources.
config :blog, BlogWeb.Endpoint,
http: [port: 4000],
http: [port: 8080],
debug_errors: true,
code_reloader: true,
check_origin: false,
Expand Down Expand Up @@ -39,8 +39,8 @@ config :phoenix, :stacktrace_depth, 20
# Configure your database
config :blog, Blog.Repo,
adapter: Ecto.Adapters.Postgres,
username: "postgres",
password: "postgres",
username: System.get_env("DATA_DB_USER") || "postgres",
password: System.get_env("DATA_DB_PASS") || "postgres",
hostname: System.get_env("DATA_DB_HOST") || "localhost",
database: "blog_dev",
hostname: "localhost",
pool_size: 10
2 changes: 1 addition & 1 deletion config/prod.exs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use Mix.Config
# which you typically run after static files are built.
config :blog, BlogWeb.Endpoint,
load_from_system_env: true,
url: [host: "example.com", port: 80],
url: [host: "example.com", port: 8080],
cache_static_manifest: "priv/static/cache_manifest.json"

# Do not print debug messages in production
Expand Down
6 changes: 3 additions & 3 deletions config/test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ config :logger, level: :warn
# Configure your database
config :blog, Blog.Repo,
adapter: Ecto.Adapters.Postgres,
username: "postgres",
password: "postgres",
username: System.get_env("DATA_DB_USER") || "postgres",
password: System.get_env("DATA_DB_PASS") || "postgres",
hostname: System.get_env("DATA_DB_HOST") || "localhost",
database: "blog_test",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox
8 changes: 8 additions & 0 deletions lib/blog_web/json.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
defmodule BlogWeb.JSON do
def encode!(data, _) do
:jiffy.encode(data, [:use_nil])
end
def decode(string) do
{:ok, :jiffy.decode(string, [:return_maps])}
end
end
112 changes: 112 additions & 0 deletions lib/blog_web/result.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
defmodule BlogWeb.OrdGraphQLResult do

@moduledoc false

# Produces data fit for external encoding from annotated value tree

alias Absinthe.{Blueprint, Phase, Type}
use Absinthe.Phase

@spec run(Blueprint.t | Phase.Error.t, Keyword.t) :: {:ok, map}
def run(%Blueprint{} = bp, _options \\ []) do
result = Map.merge(bp.result, process(bp))
{:ok, %{bp | result: result}}
end

defp process(blueprint) do
result = case blueprint.execution do
%{validation_errors: [], result: result} ->
{:ok, data(result, [])}
%{validation_errors: errors} ->
{:validation_failed, errors}
end
format_result(result)
end

defp format_result(:execution_failed) do
%{data: nil}
end
defp format_result({:ok, {data, []}}) do
%{data: data}
end
defp format_result({:ok, {data, errors}}) do
errors = errors |> Enum.uniq |> Enum.map(&format_error/1)
%{data: data, errors: errors}
end
defp format_result({:validation_failed, errors}) do
errors = errors |> Enum.uniq |> Enum.map(&format_error/1)
%{errors: errors}
end
defp format_result({:parse_failed, error}) do
%{errors: [format_error(error)]}
end

defp data(%{errors: [_|_] = field_errors}, errors), do: {nil, field_errors ++ errors}

# Leaf
defp data(%{value: nil}, errors), do: {nil, errors}
defp data(%{value: value, emitter: emitter}, errors) do
value =
case Type.unwrap(emitter.schema_node.type) do
%Type.Scalar{} = schema_node ->
Type.Scalar.serialize(schema_node, value)
%Type.Enum{} = schema_node ->
Type.Enum.serialize(schema_node, value)
end
{value, errors}
end

# Object
defp data(%{fields: fields}, errors), do: field_data(fields, errors)

# List
defp data(%{values: values}, errors), do: list_data(values, errors)

defp list_data(fields, errors, acc \\ [])
defp list_data([], errors, acc), do: {:lists.reverse(acc), errors}
defp list_data([%{errors: errs} = field | fields], errors, acc) do
{value, errors} = data(field, errors)
list_data(fields, errs ++ errors, [value | acc])
end

defp field_data(fields, errors, acc \\ [])
defp field_data([], errors, acc), do: {{:lists.reverse(acc)}, errors}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line here in the normal result phase is:

defp field_data([], errors, acc), do: {Map.new(acc), errors}

This is the only line in the entire file that is different.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The main challenge here is that for large results this function gets called a LOT, and so I want to avoid dynamic lookup. One idea is to use macros:

defmodule BlogWeb.OrdGraphQLResult do
  use Absinthe.ResultPhase
  
  def to_object_result(acc) do
    {:lists.reverse(acc)}
    # or you could do `OrdMap.new(:lists.reverse(acc))`
  end
end

defp field_data([%Absinthe.Resolution{} = res | _], _errors, _acc) do
raise """
Found unresolved resolution struct!

You probably forgot to run the resolution phase again.

#{inspect res}
"""
end
defp field_data([field | fields], errors, acc) do
{value, errors} = data(field, errors)
field_data(fields, errors, [{field_name(field.emitter), value} | acc])
end

defp field_name(%{alias: nil, name: name}), do: name
defp field_name(%{alias: name}), do: name
defp field_name(%{name: name}), do: name

defp format_error(%Phase.Error{locations: []} = error) do
error_object = %{message: error.message}
Map.merge(error.extra, error_object)
end
defp format_error(%Phase.Error{} = error) do
error_object = %{
message: error.message,
locations: Enum.flat_map(error.locations, &format_location/1),
}
error_object = case error.path do
[] -> error_object
path -> Map.put(error_object, :path, path)
end
Map.merge(Map.new(error.extra), error_object)
end

defp format_location(%{line: line, column: col}) do
[%{line: line || 0, column: col || 0}]
end
defp format_location(_), do: []
end
15 changes: 13 additions & 2 deletions lib/blog_web/router.ex
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,21 @@ defmodule BlogWeb.Router do
pipe_through :api

forward "/graphiql", Absinthe.Plug.GraphiQL,
schema: BlogWeb.Schema
schema: BlogWeb.Schema,
json_codec: BlogWeb.JSON,
pipeline: {__MODULE__, :absinthe_pipeline}

forward "/", Absinthe.Plug,
schema: BlogWeb.Schema
schema: BlogWeb.Schema,
json_codec: BlogWeb.JSON,
pipeline: {__MODULE__, :absinthe_pipeline}
end

def absinthe_pipeline(config, pipeline_opts) do
pipeline_opts = Keyword.put(pipeline_opts, :result_phase, BlogWeb.OrdGraphQLResult)
config.schema_mod
|> Absinthe.Pipeline.for_document(pipeline_opts)
|> Absinthe.Pipeline.replace(Absinthe.Phase.Document.Result, BlogWeb.OrdGraphQLResult)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Configuration here is just slightly more complicated than we want.

end

end
1 change: 1 addition & 0 deletions mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ defmodule Blog.Mixfile do
{:absinthe_ecto, ">= 0.0.0"},
{:comeonin, "~> 4.0"},
{:argon2_elixir, "~> 1.2"},
{:jiffy, ">= 0.0.0"},
]
end

Expand Down
1 change: 1 addition & 0 deletions mix.lock
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"ecto_enum": {:hex, :ecto_enum, "0.3.1", "28771a73c195553b32b434f926302092ba072ba2b50224b8d63081cad5e0846b", [], [{:ecto, ">= 0.13.1", [hex: :ecto, repo: "hexpm", optional: false]}, {:mariaex, ">= 0.3.0", [hex: :mariaex, repo: "hexpm", optional: true]}, {:postgrex, ">= 0.8.3", [hex: :postgrex, repo: "hexpm", optional: true]}], "hexpm"},
"elixir_make": {:hex, :elixir_make, "0.4.0", "992f38fabe705bb45821a728f20914c554b276838433349d4f2341f7a687cddf", [], [], "hexpm"},
"gettext": {:hex, :gettext, "0.13.1", "5e0daf4e7636d771c4c71ad5f3f53ba09a9ae5c250e1ab9c42ba9edccc476263", [], [], "hexpm"},
"jiffy": {:hex, :jiffy, "0.14.11", "919a87d491c5a6b5e3bbc27fafedc3a0761ca0b4c405394f121f582fd4e3f0e5", [:rebar3], [], "hexpm"},
"mime": {:hex, :mime, "1.1.0", "01c1d6f4083d8aa5c7b8c246ade95139620ef8effb009edde934e0ec3b28090a", [], [], "hexpm"},
"phoenix": {:hex, :phoenix, "1.3.0", "1c01124caa1b4a7af46f2050ff11b267baa3edb441b45dbf243e979cd4c5891b", [], [{:cowboy, "~> 1.0", [hex: :cowboy, repo: "hexpm", optional: true]}, {:phoenix_pubsub, "~> 1.0", [hex: :phoenix_pubsub, repo: "hexpm", optional: false]}, {:plug, "~> 1.3.3 or ~> 1.4", [hex: :plug, repo: "hexpm", optional: false]}, {:poison, "~> 2.2 or ~> 3.0", [hex: :poison, repo: "hexpm", optional: false]}], "hexpm"},
"phoenix_ecto": {:hex, :phoenix_ecto, "3.3.0", "702f6e164512853d29f9d20763493f2b3bcfcb44f118af2bc37bb95d0801b480", [], [{:ecto, "~> 2.1", [hex: :ecto, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 2.9", [hex: :phoenix_html, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm"},
Expand Down
29 changes: 29 additions & 0 deletions test/blog_web/plug_web_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
defmodule BlogWebTest do
use BlogWeb.ConnCase

@query """
{
posts {
id, title
}
}
"""
test "ordered result" do
conn = build_conn()
conn = get conn, "/api", query: @query
assert conn.resp_body == ~s({"data":{"posts":[{"id":"1","title":"Test Post"}]}})
end

@query """
{
posts {
title, id
}
}
"""
test "ordered result works in reverse" do
conn = build_conn()
conn = get conn, "/api", query: @query
assert conn.resp_body == ~s({"data":{"posts":[{"title":"Test Post","id":"1"}]}})
end
end