Created
July 25, 2018 12:19
-
-
Save quatermain/91f64d104d1a111755a35b60de9a312a to your computer and use it in GitHub Desktop.
Storage adapter for minio
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Storage.Adapters.Minio do | |
alias ExAws.S3 | |
@behaviour Storage.Adapter | |
defp root, do: Application.get_env(:storage, Storage.Adapters.Minio)[:root] | |
defp host, do: Application.fetch_env!(:storage, Storage.Adapters.Minio)[:host] | |
defp bucket, do: Application.fetch_env!(:ex_aws, :s3)[:bucket] | |
def path(components) when is_list(components) do | |
Path.join([root()] ++ components) | |
end | |
def put(%Storage.File{} = file, source) do | |
{:ok, _} = | |
source | |
|> S3.Upload.stream_file() | |
|> S3.upload(bucket(), file.path) | |
|> ExAws.request() | |
file | |
end | |
def url(path) do | |
if is_nil(host()[:url]) do | |
raise "to generate url of a stored file, first define :host option in the :storage config" | |
end | |
from = normalized_from() | |
path_from = | |
case String.starts_with?(path, from) do | |
true -> from | |
_ -> Path.join(root(), from) | |
end | |
file_path = Path.join(root(), path) | |
Path.dirname(file_path) | |
|> File.mkdir_p!() | |
{:ok, _} = | |
S3.download_file(bucket(), file_path, file_path) | |
|> ExAws.request() | |
if String.starts_with?(path, path_from) do | |
path = String.replace_leading(path, path_from, "") | |
Path.join(host()[:url], path) | |
else | |
raise "URL can be generated only for files in `#{Path.join(root(), host()[:from])}`" | |
end | |
end | |
defp normalized_from do | |
String.replace(host()[:from], ~r(\/|\\), "") | |
end | |
def delete(path) do | |
from = normalized_from() | |
path = | |
case String.starts_with?(path, from) do | |
true -> Path.join(root(), path) | |
_ -> path | |
end | |
File.rm!(path) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment