Augmenting :assoc in absinthe types

My blog app has a Post model that has many Comments.

schema "post" do
  field :title, :string
  field :content, :string

  belongs_to :owner, MyApp.Accounts.User, foreign_key: :owner_id

  has_many :comments, MyApp.Content.Comment, foreign_key: :post_id


I have an associated absinthe object as well.

object :post do
  field :id, :integer
  field :title, :string
  field :content, :string
  field :owner, :user, resolve: assoc(:owner)
  field :comments, list_of(:comment), resolve: assoc(:comments)

Queries work as expected.

Now I want to add a boolean active field to the Comment schema so that I can perform soft deletes; I’ll only select comments where active == true, and I will delete comments by setting active to false.

I add the field into my schema:

field :active, :boolean, default: true, null: false

Now I only want the absinthe :comments field to return active comments. I have a custom resolver for this…

field :comments, list_of(:comment), resolve: fn (query,_,resolution) ->
  query =
    from c in MyApp.Content.Comment,
      where: c.post_id == ^,
      where: == true,
      select: c

  {:ok, MyApp.Repo.all(query)}

I’m worried this is going to run into an N+1 problem eventually. Is there a more elegant way to do this?

Have a look at batch middleware, it is used to solve N+1 queries.

1 Like