将聚合字段添加到elixir graphql

时间:2017-12-19 15:10:27

标签: elixir phoenix-framework graphql absinthe

我正在使用苦艾酒(凤凰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:我找到了解决方案,但感觉非常黑客。

  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

1 个答案:

答案 0 :(得分:1)

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

function displayProductName($item) { 
    $productName = get_the_title($item['id']); 
    return $productName; 
} 
add_shortcode('product_name', 'displayProductName');

object :post do field :id, :integer field :title, :string field :content, :string field :likes, :integer, resolve: fn (query,_,_) -> Post.getLikeCount(query.id) end end ,解析器的arity 3匿名函数的第三个参数是resolution对象。 Absinthe.Resolution的类型为resolution.source,其中MyApp.Content.Post指的是该帖子。

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

getLikeCount/1
相关问题