aboutsummaryrefslogtreecommitdiff
path: root/lib/ejabberd/config/store.ex
blob: 72beea64ce47218d7e7bff6728895b1e8c25631d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
defmodule Ejabberd.Config.Store do
  @moduledoc """
    Module used for storing the modules parsed from
    the configuration file.

    Example:
      - Store.put(:modules, mod1)
      - Store.put(:modules, mod2)

      - Store.get(:modules) :: [mod1, mod2]

    Be carefoul: when retrieving data you get them
    in the order inserted into the store, which normally
    is the reversed order of how the modules are specified
    inside the configuration file. To resolve this just use
    a Enum.reverse/1.
  """

  @name __MODULE__

  def start_link do
    Agent.start_link(fn -> %{} end, name: @name)
  end

  @doc """
  Stores a value based on the key. If the key already exists,
  then it inserts the new element, maintaining all the others.
  It uses a list for this.
  """
  @spec put(atom, any) :: :ok
  def put(key, val) do
    Agent.update @name, &Map.update(&1, key, [val], fn coll ->
      [val | coll]
    end)
  end

  @doc """
  Gets a value based on the key passed.
  Returns always a list.
  """
  @spec get(atom) :: [any]
  def get(key) do
    Agent.get @name, &Map.get(&1, key, [])
  end

  @doc """
  Stops the store.
  It uses Agent.stop underneath, so be aware that exit
  could be called.
  """
  @spec stop() :: :ok
  def stop do
    Agent.stop @name
  end
end