Uploader v0.1.0 Uploader behaviour View Source

Link to this section Summary

Functions

Store all the uploaded files.

Link to this section Functions

Store all the uploaded files.

This function is expected to be called inside a transaction:

Multi.new()
|> Multi.insert(:user, user_changeset)
|> Multi.run(:upload_files, fn _repo, %{user: user} ->
  Uploader.store_files(user)
end)
|> Repo.transaction()
|> case do
  {:ok, %{user: user}} ->
    {:ok, user}

  {:error, :user, %Ecto.Changeset{} = changeset, _changes} ->
    {:error, changeset}

  {:error, :upload_files, {:file_path_exists, file_path}, _changes} ->
    raise "file upload failed: path \"#{file_path}\" already exists"
end

This function fetches all the uploadable schema fields (with all of their options) from the given Schema struct (see Uploader.Ecto.UploadableFields), and for each field calls the maybe_copy_file/4 callback function. This callback function is called from the module defined in the :uploader option of the field (by default, the module Uploader.LocalUploader is used). Below is an example on how to define a custom module implementing the maybe_copy_file/4 callback function in the Schema:

schema "users" do
  uploadable_field :avatar_image, uploader: AmazonS3Uploader
  # other fields
end

In case of success {:ok, nil} is returned, otherwise {:error, error_tuple} is returned with error_tuple being a two-elements tuple describing the error. This tuple is in fact the returned error value of the call to the maybe_copy_file/4 function. An example of a returned error value is {:error, {:file_path_exists, file_path}}.

Link to this section Callbacks

Link to this callback

maybe_copy_file(tmp_file_path, new_file_path, on_file_exists)

View Source
maybe_copy_file(
  tmp_file_path :: String.t(),
  new_file_path :: String.t(),
  on_file_exists :: atom() | nil
) :: :ok | {:error, term()}