将聚合字段添加到elixir graphql

问题描述 投票:0回答:1

我正在使用苦艾酒与长生不老药(凤凰1.3)。我有一个包含用户,帖子和喜欢的博客应用程序,喜欢加入用户和帖子之间的多对多关系。

  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

假设我想在后端而不是前端聚合它们。我想:liked_by只是计算所有存在的喜欢,更像field :likes, :int,所以我可以得到这样的回复:

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

我的对象会是什么样子?我想做这样的事情:

  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

编辑#1:更具体地说,我想知道如何参数化absinthe对象中的匿名函数。我可以让对象轻松返回非参数化值:

field :somenumber, :integer, resolve: fn (_,_) -> {:ok, 15} end

但是添加一个这样的参数

field :somenumber, :integer, resolve: fn (foo,_) -> {:ok, foo} end

返回以下内容:

...
"somenumber": {},
...

如何传入对象的id或隐式关联的查询?

编辑#2:我已经找到了解决方案,但感觉非常hacky。

  object :post do
    field :id, :integer
    field :title, :string
    field :content, :string
    field :likes, :integer, resolve: fn (_,_,resolution) ->
      {:ok, Post.getLikeCount(resolution.source.id) }
    end
  end
elixir phoenix-framework graphql absinthe
1个回答
1
投票

按照@ mudasobwa的建议,我有这个解决方案:

 object :post do
    field :id, :integer
    field :title, :string
    field :content, :string
    field :likes, :integer, resolve: fn (query,_,_) ->
      Post.getLikeCount(query.id)
    end
  end

resolution,解析器的arity 3匿名函数的第三个参数,是Absinthe.Resolution对象。 resolution.sourceMyApp.Content.Post类型,其中id指的是Post。

然后我在Post.ex中添加了一个名为getLikeCount/1的函数,它可以获得喜欢的数量。

  def getLikeCount (post_id) do
    query =
      from l in MyApp.Content.Likes,
        where: l.post_id == ^post_id,
        select: count("*")

    case Repo.one(query) do
      nil -> {:error, "Error getting like count for post #{post_id}"}
      likes -> {:ok, likes}
    end
  end
© www.soinside.com 2019 - 2024. All rights reserved.