1.7 KiB · text History 1ba5ec3
defmodule CartosnapApp.Storage do
  @moduledoc """
  Where photo files live: a Backblaze B2 bucket, spoken to through B2's
  S3-compatible API (signed by Req; see `CartosnapApp.Storage.S3`).

  Keys are `"<user id>/<photo id>/<variant>.<ext>"`; see `key/3`. The bucket
  is public-read, so a key turns into a URL with `public_url/1` and the
  browser fetches the image straight from B2.

  The backend is swappable (`config :cartosnap_app, :storage, Module`):
  development keeps files on disk (`CartosnapApp.Storage.Local`, unless
  `STORAGE=s3`) and tests keep them in memory (`CartosnapApp.Storage.Fake`).
  """

  @callback put(key :: String.t(), body :: binary(), content_type :: String.t()) ::
              :ok | {:error, term()}
  @callback get(key :: String.t()) :: {:ok, binary()} | {:error, term()}
  @callback delete(key :: String.t()) :: :ok | {:error, term()}
  @callback url(key :: String.t()) :: String.t()

  @variants ~w(orig full prev thumb)

  @doc "The object key for one variant (`orig`, `full`, `prev`, `thumb`) of a photo."
  def key(%{user: user_id, id: photo_id}, variant, ext) when variant in @variants,
    do: "#{user_id}/#{photo_id}/#{variant}.#{ext}"

  def put(key, body, content_type), do: backend().put(key, body, content_type)
  def get(key), do: backend().get(key)
  def delete(key), do: backend().delete(key)

  @doc "A browser-fetchable URL for `key`, or nil for a missing key."
  def public_url(nil), do: nil

  def public_url(key) when is_binary(key), do: backend().url(key)

  @doc false
  def bucket, do: Application.fetch_env!(:cartosnap_app, :uploads)[:bucket]

  defp backend, do: Application.get_env(:cartosnap_app, :storage, CartosnapApp.Storage.S3)
end