簡體   English   中英

將聚合字段添加到Elixir graphql

[英]Adding aggregate fields to elixir graphql

我正在用苦艾酒和長生不老葯(鳳凰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可以簡單地統計所有存在的點: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

在遵循@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.source的類型為MyApp.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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM