894 B · text History 44bc4f7
defmodule CartosnapApp.Storage.Fake do
  @moduledoc """
  An in-memory storage backend for tests. Objects live in an Agent started
  on first use; `CartosnapApp.Storage.Fake.objects/0` shows what was written.
  """

  @behaviour CartosnapApp.Storage

  @impl true
  def put(key, body, _content_type) do
    Agent.update(agent(), &Map.put(&1, key, body))
  end

  @impl true
  def get(key) do
    case Agent.get(agent(), &Map.fetch(&1, key)) do
      {:ok, body} -> {:ok, body}
      :error -> {:error, :not_found}
    end
  end

  @impl true
  def delete(key) do
    Agent.update(agent(), &Map.delete(&1, key))
  end

  @impl true
  def url(key), do: "https://fake-storage.test/#{key}"

  def objects, do: Agent.get(agent(), & &1)

  defp agent do
    case Agent.start(fn -> %{} end, name: __MODULE__) do
      {:ok, pid} -> pid
      {:error, {:already_started, pid}} -> pid
    end
  end
end