Absinthe models that aggregate types

I am using absinthe with elixir (phoenix 1.3). I have a blog app that has Users, Posts, and Likes, and the likes are joined with a many-to-many relationship between Users and Posts.

  schema "users" do
    field :email, :string
    field :handle, :string 
    many_to_many :liked_posts, MyApp.Content.Post, join_through: "likes"
  end

  schema "posts" do
    field :title, :string
    field :content, :string 
    many_to_many :liking_users, MyApp.Accounts.User, join_through: "likes"
  end

  schema "likes" do
    belongs_to :user, MyApp.Accounts.User
    belongs_to :post, MyApp.Content.Post
  end

Let’s say I want to aggregate them on the backend rather than the front. I would like :liked_by to simply be a count of all the likes that exist, more like field :likes, :int, so that I can get back responses like this:

{
  "data": {
    "post" : {
      "title" : "Title",
      "content" : "This is the content",
      "likes" : 7
    }
  }
}

What would my object have to look like? I want to do something like this:

  object :post do
    field :id, :integer
    field :title, :string
    field :content, :string
    field :likes, :integer, resolve: assoc(:liking_users, fn query, id, _ ->
       query |> from like in MyApp.Content.Like, where: like.post_id == ^id, select: count("*")
    )
  end
2 Likes

Yes You can.

Passing an anonymous function as second parameters give You access to query.

field :likes, :integer, resolve: assoc(:liking_users, fn query, _, _ -> 
  query |> PUT_COUNT_RECORDS_HERE
end)

The second parameter of the anonymous function is the argument, while the third is the context.

I am not sure of the count form, maybe try

select(count([:id]))

As an example, I am using this form to sort records before returning the result.

    field :game_nodes, list_of(:game_node), resolve: assoc(:nodes, fn query, _, _ -> 
      query |> order_by(asc: :index)
    end)
2 Likes

Getting closer, still getting errors though. See edit above.

1 Like