Skip to content

Instantly share code, notes, and snippets.

@bruce
Created March 27, 2017 21:37
Show Gist options
  • Save bruce/52b1528af5ce446eb24eae3cd32b6af7 to your computer and use it in GitHub Desktop.
Save bruce/52b1528af5ce446eb24eae3cd32b6af7 to your computer and use it in GitHub Desktop.
Adding a count to an absinthe_relay Connection
{
items(first: 5) {
count
edges {
node {
name
}
}
}
}
{
"data": {
"items": {
"edges": [
{
"node": {
"name": "Item #1"
}
},
{
"node": {
"name": "Item #2"
}
},
{
"node": {
"name": "Item #3"
}
},
{
"node": {
"name": "Item #4"
}
},
{
"node": {
"name": "Item #5"
}
}
],
"count": 1000
}
}
}
defmodule ScrogsoApp.Web.Schema do
use Absinthe.Schema
use Absinthe.Relay.Schema
import Ecto.Query
alias ScrogsonApp.{Example, Repo}
connection node_type: :item do
field :count, non_null(:integer)
edge do
# Because we're extending the connection type, we need to
# manually force the edge type to be created with this macro.
end
end
node interface do
resolve_type fn
%Example.Item{}, _ ->
:item
_, _ ->
nil
end
end
node object :item do
field :name, :string
end
query do
connection field :items, node_type: :item do
resolve fn args, _ ->
# Simple query w/out filtering, etc
query = from t in Example.Item
count = Repo.one!(from item in query, select: count(item.id))
result =
Absinthe.Relay.Connection.from_query(query, &Repo.all/1, args)
|> Map.put(:count, count)
{:ok, result}
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment