Created
November 5, 2016 15:39
-
-
Save MartinElvar/c1fa40399cf56eb6bf8da3e559d3e487 to your computer and use it in GitHub Desktop.
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 ApiEndpoint.Schema.Helpers do | |
def has_many({model, foreign_key}, ids) do | |
import Ecto.Query | |
model | |
|> where([m], field(m, ^foreign_key) in ^ids) | |
|> Storages.Repo.all | |
|> Enum.group_by(fn storage -> Map.get(storage, foreign_key) end) | |
end | |
end | |
defmodule Users.Types do | |
use Absinthe.Schema.Notation | |
object :user do | |
field :id, :id | |
field :first_name, :string | |
field :last_name, :string | |
field :email, :string | |
field :phone, :string | |
field :storages, list_of(:storage) do | |
resolve fn user, _, _ -> | |
batch({ApiEndpoint.Schema.Helpers, :has_many, {Storages.Storage, :user_id}}, user.id, fn batch_result -> | |
{:ok, Map.get(batch_result, user.id, [])} | |
end) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment