Skip to content

Instantly share code, notes, and snippets.

@ctrlShiftBryan
Created November 5, 2020 12:53
Show Gist options
  • Save ctrlShiftBryan/c0b66c98067e42d8f48f332ff33a4069 to your computer and use it in GitHub Desktop.
Save ctrlShiftBryan/c0b66c98067e42d8f48f332ff33a4069 to your computer and use it in GitHub Desktop.
elixir absinth string key map middle ware
# We are changing absithe here so that it expects maps with string keys instead
# of maps with atom keys when it resolves :user object
#
# Out of the box absinthe is optimized for using with something like ecto
# that would normally use an ecto schema (which have atom keys).
# Instead we are working with api responses and we don't need
# the overhead converting our maps to maps with atom keys.
def middleware(
middleware,
%{identifier: identifier} = field,
%{identifier: object_identifier} = object
)
when object_identifier in [:user, :user_info] do
middleware_spec = {{__MODULE__, :get_string_key}, Atom.to_string(identifier)}
Absinthe.Schema.replace_default(middleware, middleware_spec, field, object)
end
# if it's any other object keep things as is
def middleware(middleware, _field, _object), do: middleware
def get_string_key(%{source: source} = res, key) do
%{res | state: :resolved, value: Map.get(source, key)}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment