philomena/lib/philomena/image_faves.ex

55 lines
1.1 KiB
Elixir
Raw Normal View History

2019-11-17 00:42:41 +01:00
defmodule Philomena.ImageFaves do
@moduledoc """
The ImageFaves context.
"""
import Ecto.Query, warn: false
2019-11-17 03:20:33 +01:00
alias Ecto.Multi
2019-11-17 00:42:41 +01:00
2019-11-17 03:20:33 +01:00
alias Philomena.Images.Image
2019-11-17 00:42:41 +01:00
alias Philomena.ImageFaves.ImageFave
@doc """
2019-11-17 03:20:33 +01:00
Creates a image_hide.
2019-11-17 00:42:41 +01:00
"""
2019-11-17 03:20:33 +01:00
def create_fave_transaction(image, user) do
fave =
%ImageFave{image_id: image.id, user_id: user.id}
|> ImageFave.changeset(%{})
image_query =
Image
|> where(id: ^image.id)
Multi.new
|> Multi.insert(:fave, fave)
|> Multi.update_all(:inc_faves_count, image_query, inc: [faves_count: 1])
2019-11-17 00:42:41 +01:00
end
@doc """
Deletes a ImageFave.
"""
2019-11-17 03:20:33 +01:00
def delete_fave_transaction(image, user) do
fave_query =
ImageFave
|> where(image_id: ^image.id)
|> where(user_id: ^user.id)
image_query =
Image
|> where(id: ^image.id)
Multi.new
|> Multi.delete_all(:unfave, fave_query)
|> Multi.run(:dec_faves_count, fn repo, %{unfave: {faves, nil}} ->
{count, nil} =
image_query
|> repo.update_all(inc: [faves_count: -faves])
{:ok, count}
end)
2019-11-17 00:42:41 +01:00
end
end