Created
January 29, 2019 20:40
-
-
Save hadfieldn/80bb2d825cc68c316009bc591a018a22 to your computer and use it in GitHub Desktop.
Medium: AbsintheSortingCodec
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule AbsintheSortingCodec do | |
@moduledoc """ | |
Convert the JSON output of an introspection query into deterministic JSON with types ordered alphabetically. | |
""" | |
def encode(schema, opts \\ []) do | |
schema | |
|> sorted_objects() | |
|> Jason.encode(opts) | |
end | |
def encode!(schema, opts \\ []) do | |
case encode(schema, opts) do | |
{:ok, content} -> content | |
{:error, reason} -> raise reason | |
end | |
end | |
defp sorted_objects(value) | |
defp sorted_objects(map) when is_map(map) do | |
for {key, val} <- map, into: %{}, do: {key, sorted_objects(val)} | |
end | |
defp sorted_objects(list) when is_list(list) do | |
list | |
|> Enum.sort_by(&list_sorting_value/1) | |
|> Enum.map(&sorted_objects/1) | |
end | |
defp sorted_objects(value), do: value | |
defp list_sorting_value(%{name: name}), do: name | |
defp list_sorting_value(%{"name" => name}), do: name | |
defp list_sorting_value(value), do: value | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment