Packages

Tempel is a file attachment management for elixir web project

Current section

Files

Jump to
tempel lib tempel local.ex
Raw

lib/tempel/local.ex

defmodule Tempel.Local do
@spec init(opts :: map()) :: map()
def init(opts), do: opts
@spec save(file :: Tempel.Gate.file() | Tempel.Gate.fileio(), map) ::
{:ok, filename :: binary()} | {:error, reason :: any}
def save(file, opts) do
filename = get_atom_or_string(file, :filename)
if iodata = get_atom_or_string(file, :iodata) do
write_io(iodata, filename, opts)
else
write_file(get_atom_or_string(file, :path), filename, opts)
end
end
@spec delete(map, any) :: :ok | {:error, reasonn :: any}
def delete(opts, files) do
storage_path = Map.get(opts, :storage_path)
result =
Enum.reduce(files, [], fn file, acc ->
file_path = Path.join(storage_path, file)
if io().exists?(file_path) do
case io().rm(file_path) do
:ok -> acc
{:error, _} -> acc ++ [file_path]
end
else
acc
end
end)
case result do
[] -> :ok
failed_keys -> {:error, failed_keys}
end
end
@spec to_url(opts :: map, object_key :: binary) :: binary
def to_url(opts, object_key) do
Map.get(opts, :object_path) <> object_key
end
@spec write_file(path :: Path.t() | binary(), filename :: binary(), opts :: map()) ::
{:ok, filename :: binary()} | {:error, reason :: any()}
defp write_file(path, filename, opts) do
storage_path = Map.get(opts, :storage_path)
case io().cp(path, Path.absname(Path.join(storage_path, filename))) do
:ok -> {:ok, filename}
err -> err
end
end
@spec write_io(iodata :: binary(), filename :: binary(), opts :: map()) ::
{:ok, filename :: binary()} | {:error, reason :: any()}
defp write_io(iodata, filename, opts) do
storage_path = Map.get(opts, :storage_path)
mode = Map.get(opts, :mode) || [:binary]
case io().write(Path.absname(Path.join(storage_path, filename)), iodata, mode) do
:ok -> {:ok, filename}
err -> err
end
end
@spec io :: module()
defp io() do
Application.get_env(:tempel_local, :io, File)
end
@spec get_atom_or_string(map :: map(), key :: atom) :: any()
defp get_atom_or_string(map, key) do
Map.get(map, key) || Map.get(map, Atom.to_string(key))
end
end