Merge branch 'develop' into openapi/account
[akkoma] / lib / pleroma / counter_cache.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.CounterCache do
6 alias Pleroma.CounterCache
7 alias Pleroma.Repo
8 use Ecto.Schema
9 import Ecto.Changeset
10 import Ecto.Query
11
12 schema "counter_cache" do
13 field(:name, :string)
14 field(:count, :integer)
15 end
16
17 def changeset(struct, params) do
18 struct
19 |> cast(params, [:name, :count])
20 |> validate_required([:name])
21 |> unique_constraint(:name)
22 end
23
24 def get_as_map(names) when is_list(names) do
25 CounterCache
26 |> where([cc], cc.name in ^names)
27 |> Repo.all()
28 |> Enum.group_by(& &1.name, & &1.count)
29 |> Map.new(fn {k, v} -> {k, hd(v)} end)
30 end
31
32 def set(name, count) do
33 %CounterCache{}
34 |> changeset(%{"name" => name, "count" => count})
35 |> Repo.insert(
36 on_conflict: [set: [count: count]],
37 returning: true,
38 conflict_target: :name
39 )
40 end
41 end