2019-11-17 19:52:59 +01:00
|
|
|
defmodule PhilomenaWeb.NotificationCountPlug do
|
|
|
|
@moduledoc """
|
|
|
|
This plug stores the current notification count.
|
|
|
|
|
|
|
|
## Example
|
|
|
|
|
|
|
|
plug PhilomenaWeb.NotificationCountPlug
|
|
|
|
"""
|
|
|
|
|
|
|
|
alias Plug.Conn
|
|
|
|
alias Philomena.Conversations
|
|
|
|
alias Philomena.Notifications
|
|
|
|
|
|
|
|
@doc false
|
|
|
|
@spec init(any()) :: any()
|
|
|
|
def init(opts), do: opts
|
|
|
|
|
2019-12-02 15:55:48 +01:00
|
|
|
@doc false
|
|
|
|
@spec call(Plug.Conn.t()) :: Plug.Conn.t()
|
|
|
|
def call(conn), do: call(conn, nil)
|
|
|
|
|
2019-11-17 19:52:59 +01:00
|
|
|
@doc false
|
|
|
|
@spec call(Plug.Conn.t(), any()) :: Plug.Conn.t()
|
|
|
|
def call(conn, _opts) do
|
2020-07-28 22:56:26 +02:00
|
|
|
user = conn.assigns.current_user
|
2019-11-17 19:52:59 +01:00
|
|
|
|
|
|
|
conn
|
|
|
|
|> maybe_assign_notifications(user)
|
|
|
|
|> maybe_assign_conversations(user)
|
|
|
|
end
|
|
|
|
|
|
|
|
defp maybe_assign_notifications(conn, nil), do: conn
|
2020-01-11 05:20:19 +01:00
|
|
|
|
2019-11-17 19:52:59 +01:00
|
|
|
defp maybe_assign_notifications(conn, user) do
|
2024-07-08 00:09:20 +02:00
|
|
|
notifications = Notifications.total_unread_notification_count(user)
|
2019-11-17 19:52:59 +01:00
|
|
|
|
2020-07-28 22:56:26 +02:00
|
|
|
Conn.assign(conn, :notification_count, notifications)
|
2019-11-17 19:52:59 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
defp maybe_assign_conversations(conn, nil), do: conn
|
2020-01-11 05:20:19 +01:00
|
|
|
|
2019-11-17 19:52:59 +01:00
|
|
|
defp maybe_assign_conversations(conn, user) do
|
|
|
|
conversations = Conversations.count_unread_conversations(user)
|
|
|
|
|
2020-07-28 22:56:26 +02:00
|
|
|
Conn.assign(conn, :conversation_count, conversations)
|
2019-11-17 19:52:59 +01:00
|
|
|
end
|
2020-01-11 05:20:19 +01:00
|
|
|
end
|