aboutsummaryrefslogtreecommitdiff
path: root/lib/config.ex
blob: 8778e5bbecba61184aae599fd3c27f82063050ee (plain)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
defmodule Mailchimp.Config do
  use GenServer

  defstruct api_key: nil, api_version: "3.0"

  require Logger

  # Public API

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

  def start_link do
    config = %__MODULE__{
      api_key: get_api_key_from_config,
      api_version: get_api_version_from_config
    }

    Agent.start_link(fn -> config end, name: __MODULE__)
  end

  def root_endpoint do
    Agent.get(__MODULE__, fn %{api_key: api_key, api_version: api_version} ->
      {:ok, shard} = get_shard(api_key)
      "https://#{shard}.api.mailchimp.com/#{api_version}/"
    end)
  end

  def api_key do
    Agent.get(__MODULE__, fn %{api_key: api_key} -> api_key end)
  end

  def api_version do
    Agent.get(__MODULE__, fn %{api_version: api_version} -> api_version end)
  end

  def update(config) when is_list(config) do
    Agent.update(__MODULE__, fn current_config ->
      Enum.reduce(config, current_config, fn({k,v}, acc) -> Map.put(acc, k, v) end)
    end)
  end

  # Private methods

  defp sanitize_api_key({:system, env_var}) do
    sanitize_api_key System.get_env(env_var)
  end

  defp sanitize_api_key(api_key) do
    api_key
  end

  defp get_api_key_from_config do
    sanitize_api_key(Application.get_env(:mailchimp, :apikey)) || sanitize_api_key(Application.get_env(:mailchimp, :api_key))
  end

  defp get_api_version_from_config do
    Application.get_env(:mailchimp, :api_version) || "3.0"
  end

  defp get_shard(api_key) do
    shard = api_key
            |> String.split(~r{-})
            |> List.last

    case shard do
      nil ->
        Logger.error "[mailchimp] This doesn't look like an API Key: #{api_key}"
        Logger.error "[mailchimp] The API Key should have both a key and a server name, separated by a dash, like this: abcdefg8abcdefg6abcdefg4-us1"
        :error

      _ ->
        {:ok, shard}
    end
  end
end