Skip to content

Instantly share code, notes, and snippets.

@icidasset
Last active February 15, 2016 20:09
Show Gist options
  • Save icidasset/4146a452603150d052fb to your computer and use it in GitHub Desktop.
Save icidasset/4146a452603150d052fb to your computer and use it in GitHub Desktop.
Ecto + GraphQL example
defmodule App.GraphQL.Helpers do
alias GraphQL.Type.{ID, List}
def build_definition(model, :single) do
%{
type: build_type(model),
args: %{ id: %{ type: ID }},
resolve: &model.resolve/3,
}
end
def build_definition(model, :multiple) do
%{
type: %List{ ofType: build_type(model) },
resolve: &model.resolve/3,
}
end
defp build_type(model) do
Ectograph.Schema.cast_schema(model, :ecto_to_graphql)
end
end
defmodule App.GraphQL.Schema do
alias App.GraphQL.{Helpers}
alias App.{Models}
def schema do
%GraphQL.Schema{
query: %GraphQL.Type.ObjectType{
name: "Queries",
description: "API Queries",
fields: %{
map: Helpers.build_definition(Models.Map, :single),
maps: Helpers.build_definition(Models.Map, :multiple),
}
},
mutation: %GraphQL.Type.ObjectType{
name: "Mutations",
description: "API Mutations",
fields: %{},
}
}
end
end
defmodule App.Models.Map do
use Ecto.Schema
schema "map" do
field :key, :string
field :name, :string
timestamps
end
def resolve(_, %{ id: id }, _) do
# do database query for one specific map (by id)
end
def resolve(_, _, _) do
# do database query for all maps
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment