Skip to content

Instantly share code, notes, and snippets.

@bruce
Created April 27, 2017 15:36
Show Gist options
  • Save bruce/160a69373e1e002764176bf7cf3b3195 to your computer and use it in GitHub Desktop.
Save bruce/160a69373e1e002764176bf7cf3b3195 to your computer and use it in GitHub Desktop.
Node interface type guessing
defmodule MyApp.Web.Schema.Types do
use Absinthe.Schema.Notation
use Absinthe.Relay.Schema.Notation
node interface do
resolve_type fn
# Guess type from struct name:
# Example: MyApp.Model.Foo -> :foo
%{__struct__: str}, _ ->
str
|> model_to_node_type
value, _ ->
Logger.warn "Could not extract node type from value: #{inspect value}"
nil
end
end
# ...
@doc """
Given a model name, return the matching node type
(Absinthe type identifier).
## Examples
```
iex> model_to_node_type(MyApp.Model.AssetType)
:asset_type
```
"""
@spec model_to_node_type(atom) :: atom
def model_to_node_type(model) do
["MyApp", "Model", name] = Module.split(model)
name
|> Macro.underscore
|> String.to_existing_atom
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment